PyQt5: How can I connect a QPushButton to a slot?

前端 未结 1 1637
无人共我
无人共我 2020-12-30 08:25

Okay, so pretty much every tutorial/understandable-written-in-human-language-documentation is for PyQt4. But, PyQt5 changed how the whole \'connect button to a slot\' works,

相关标签:
1条回答
  • 2020-12-30 09:05

    I don't know where you got the idea that "PyQt5 changed how the whole 'connect button to a slot' works", but it is completely and utterly wrong. There have been no such changes, as can be readily seen from the official PyQt documentation:

    • PyQt4 Signals & Slots documentation
    • PyQt5 Signals & Slots documentation

    But even without reading any documentation, it's easy enough to test for yourself. For example, in the following script, just switch comments on the first two lines, and it will run just the same:

    # from PyQt5.QtWidgets import (
    from PyQt4.QtGui import (
        QApplication, QWidget, QVBoxLayout, QPushButton, QLabel,
        )
    
    class Window(QWidget):
        def __init__(self):
            super(Window, self).__init__()
            self.button = QPushButton('Test', self)
            self.label = QLabel(self)
            self.button.clicked.connect(self.handleButton)
            layout = QVBoxLayout(self)
            layout.addWidget(self.label)
            layout.addWidget(self.button)
    
        def handleButton(self):
            self.label.setText('Button Clicked!')
    
    if __name__ == '__main__':
    
        import sys
        app = QApplication(sys.argv)
        window = Window()
        window.show()
        sys.exit(app.exec_())
    

    As for the other points: at your current state of knowledge, I would say you can safely ignore connectSlotsByName and pyqtSlot. Although they have their uses (see the above docs for details), there's very rarely any real need to use them in 95% of applications.

    For your specific case, the syntax is simply:

        self.testButton.clicked.connect(self.change_text)
        ...
    
    def change_text(self):
        self.ui.testLabel.setText("Button Clicked!")
    
    0 讨论(0)
提交回复
热议问题