1

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 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Many thanks, I was stuck for hours and literally going nowhere, much appreciated!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.