PyQT 按钮单击不起作用 [英] PyQT Button click doesn't work

查看:59
本文介绍了PyQT 按钮单击不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我的问题是,我不想为一堆按钮手动编写大量代码,而是想为 QPushButton 创建一个类,然后在调用该类创建时更改这么多变量我的个人按钮.

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.

我的问题是,尽管调用了 clicked.connect 函数并且在运行代码时没有错误,但我的按钮似乎无法点击.以下是按钮类的相关部分:

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)

推荐答案

您应该在 __init__ 方法上执行与 clicked 信号的连接:

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_()

您可以运行它,每次单击按钮时都会看到 Hello 打印在控制台上.

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

retranslateUi 方法适用于 i18n.您可以查看这里.

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

这篇关于PyQT 按钮单击不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆