Home > Blockchain >  QTableWidget return current item but return previous value when clicked
QTableWidget return current item but return previous value when clicked

Time:08-25

Im trying to write function: when click to one value in QtableWidget, this value will show up on lineEdit. But i have a problem: the return value is previous value and i must click one more time,lineEdit just returns the current value.

  • Ex: two value: 0,1. frist click (value 0): return empty, 2nd click (value 0): return 0, 3rd click (value 1): return 0, 4th click(value 1): return 1.
  • My code:
    class ClickableList(QTableWidget):
        clicked = pyqtSignal()
        def mousePressEvent(self, event):
            self.clicked.emit()
            QTableWidget.mousePressEvent(self, event) 
    class Ui_FormCam(object):
        def setupUi(self, Form):
            

             ...
        
             self.lineEdit = QtWidgets.QLineEdit()
             self.lineEdit.setObjectName("lineEdit")
             self.horizontalLayout_2.addWidget(self.lineEdit)
             ...
             self.tableWidget = ClickableList(Form)
             self.tableWidget.setGeometry(QtCore.QRect(90, 20, 256, 192))
             self.tableWidget.setObjectName("tableWidget")
             self.tableWidget.setColumnCount(3)
        
             item = QtWidgets.QTableWidgetItem()
             self.tableWidget.setHorizontalHeaderItem(0, item)
             item = QtWidgets.QTableWidgetItem()
             self.tableWidget.setHorizontalHeaderItem(1, item)
             item = QtWidgets.QTableWidgetItem()
             self.tableWidget.setHorizontalHeaderItem(2, item)
             
             ...
             self.tableWidget.clicked.connect(self.getTextFromList)
             ...
       def getTextFromList(self):
             # print(self.tableWidget.item(0,0).text())
         self.lineEdit.setText(self.tableWidget.currentItem().text())

CodePudding user response:

You can use the builtin .currentCellChanged or .currentItemChanged signal instead of .clicked one then the callback will be called with the parameters of the old and new cell index if you use the cell version, or the old value and new value if you use the item version.

For example:

self.tableWidget.currentItemChanged.connect(self.getTextFromList)

def getTextFromList(self, old_value, new_value):
    self.lineEdit.setText(new_value.text())
  • Related