1
votes

I want to make some data hidden in QTableWidget until a specific cell is clicked. Right now I only manage to display "*" instead of actual value. I think I could connect somehow with action when the specific cell is clicked and replaced the value of the clicked cell. I also know that there is a function setData() that can be invoked on QTableWidgetItem and give me wanted behavior. But I cannot find any useful example for Python implementation of qt. What is the best solution to this problem?

def setTableValues(self):
    self.table.setRowCount(len(self.tableList))
    x = 0
    for acc in self.tableList:
        y = 0
        for val in acc.getValuesAsList():
            if isinstance(val,Cipher):
                val = "*"*len(val.getDecrypted())
            item = QTableWidgetItem(val)
            self.table.setItem(x,y,item)
            y += 1
        x += 1
    self.table.resizeRowsToContents()
    self.table.resizeColumnsToContents()
1

1 Answers

2
votes

You can associate a flag with a role that indicates the visibility of the text and then use a delegate to hide the text. That flag will change when the items are pressed:

from PyQt5 import QtCore, QtGui, QtWidgets

VisibilityRole = QtCore.Qt.UserRole + 1000


class VisibilityDelegate(QtWidgets.QStyledItemDelegate):
    def initStyleOption(self, option, index):
        super().initStyleOption(option, index)
        if not index.data(VisibilityRole):
            option.text = "*" * len(option.text)


class TableWidget(QtWidgets.QTableWidget):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        delegate = VisibilityDelegate(self)
        self.setItemDelegate(delegate)
        self.visibility_index = QtCore.QModelIndex()
        self.pressed.connect(self.on_pressed)

    @QtCore.pyqtSlot(QtCore.QModelIndex)
    def on_pressed(self, index):
        if self.visibility_index.isValid():
            self.model().setData(self.visibility_index, False, VisibilityRole)
        self.visibility_index = index
        self.model().setData(self.visibility_index, True, VisibilityRole)


if __name__ == "__main__":
    import sys

    app = QtWidgets.QApplication(sys.argv)

    w = TableWidget(10, 4)
    for i in range(w.rowCount()):
        for j in range(w.columnCount()):
            it = QtWidgets.QTableWidgetItem("{}-{}".format(i, j))
            w.setItem(i, j, it)
    w.show()
    w.resize(640, 480)

    sys.exit(app.exec_())