Search code examples
pythonpython-3.xpyside2

get button text using sender() always return error — 'NoneType' object has no attribute 'text'


Using Qt Designer created a Push Button, then code:

# import ...
class Test:
    def __init__(self):
        qfile = QFile("test.ui")
        qfile.open(QFile.ReadOnly)
        qfile.close()
        self.ui = QUiLoader().load(qfile)
        self.ui.pushButton.clicked.connect(self.buttonClicked)

    def buttonClicked(self):
        print(self.ui.sender().text())

app = QApplication([])
test = Test()
test.ui.show()
app.exec_()

When I clicked the button, getting error message:

AttributeError: 'NoneType' object has no attribute 'text'

How can I get the button text?


Solution

  • The sender() method returns the object that emitted the signal if where it is invoked is a method that is called asynchronously, also only the sender() of the class to which the method belongs will be valid.

    Considering the above, the Test class must be a QObject, and its sender() method must be invoked:

    import os
    
    from PySide2 import QtCore, QtWidgets, QtUiTools
    
    CURRENT_DIRECTORY = os.path.dirname(os.path.realpath(__file__))
    
    
    class Test(QtCore.QObject):
        def __init__(self):
            super().__init__()
            filename = os.path.join(CURRENT_DIRECTORY, "test.ui")
            qfile = QtCore.QFile(filename)
            qfile.open(QtCore.QFile.ReadOnly)
            qfile.close()
            self.ui = QtUiTools.QUiLoader().load(qfile)
            self.ui.pushButton.clicked.connect(self.buttonClicked)
    
        @QtCore.Slot()
        def buttonClicked(self):
            print(self.sender().text())
    
    
    if __name__ == "__main__":
    
        app = QtWidgets.QApplication([])
        test = Test()
        test.ui.show()
        app.exec_()