PyQT Button click doesn't work

2019-08-05 09:19发布

问题:

So my problem is that instead of manually writing a ton of code for a bunch of buttons, I want to create a class for a QPushButton and then change so many variables upon calling that class to create my individual buttons.

My problem is that my button does not seem to be clickable despite calling the clicked.connect function and having no errors upon running the code. Here are the relevant parts of the button class:

class Button(QtGui.QPushButton):
    def __init__(self, parent):
        super(Button, self).__init__(parent)
        self.setAcceptDrops(True)

        self.setGeometry(QtCore.QRect(90, 90, 61, 51))
        self.setText("Change Me!")

    def retranslateUi(self, Form):
        self.clicked.connect(self.printSomething)

    def printSomething(self):
        print "Hello"

Here is how I call the button class:

class MyWindow(QtGui.QWidget):
    def __init__(self):
        super(MyWindow,self).__init__()
        self.btn = Button(self)

        layout = QtGui.QVBoxLayout(self)
        layout.addWidget(self.btn)
        self.setLayout(layout)

回答1:

You should perform the connection to the clicked signal on the __init__ method:

from PyQt4 import QtGui,QtCore

class Button(QtGui.QPushButton):
    def __init__(self, parent):
        super(Button, self).__init__(parent)
        self.setAcceptDrops(True)

        self.setGeometry(QtCore.QRect(90, 90, 61, 51))
        self.setText("Change Me!")
        self.clicked.connect(self.printSomething) #connect here!

    #no need for retranslateUi in your code example

    def printSomething(self):
        print "Hello"

class MyWindow(QtGui.QWidget):
    def __init__(self):
        super(MyWindow,self).__init__()
        self.btn = Button(self)

        layout = QtGui.QVBoxLayout(self)
        layout.addWidget(self.btn)
        self.setLayout(layout)


app = QtGui.QApplication([])
w = MyWindow()
w.show()
app.exec_()

You can run it and will see the Hello printed on the console every time you click the button.

The retranslateUi method is for i18n. You can check here.