PyQT Button click doesn't work

做~自己de王妃 提交于 2019-12-11 12:02:59

问题


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.



来源:https://stackoverflow.com/questions/29807630/pyqt-button-click-doesnt-work

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!