python - PyQT中事件的识别源

标签 python user-interface qt pyqt pyqt4

我刚开始使用 PyQt4,但现在我遇到了事件问题。

我有一个主类,假设是 MainWindow。 MainWindow 有一个 ButtonX 类型的按钮列表(继承自 QPushButton)。我想实现 2 个解决方案之一(取决于哪个更容易)。

1) 单击列表中的一个按钮后,我想运行 MainWindow 的一种方法。我希望能够在那里读取事件源(识别单击的按钮)

2) 第二种解决方案是运行 ButtonX 类中定义的方法。

我尝试的是:

QtCore.QObject.connect(self.getButton(0, 0), QtCore.SIGNAL("clicked()"), self.getButton(0, 0).buttonMethod())

QtCore.QObject.connect(self.getButton(0, 0), QtCore.SIGNAL("clicked()"), self.getButton(0, 0), QtCore.SLOT("incrementValue()"))

甚至这一行也会暂停 Python 解释器

QtCore.QObject.connect(self.getButton(0, 0), QtCore.SIGNAL("clicked()"), self.getButton(0, 0), QtCore.SLOT("incrementValue"))

最佳答案

1) After click one of the button from the list I would like to run a one method of MainWindow. I would like to be able to read a source of event there (recognize clicked button)

您可以使用 QObject.sender() 访问事件源.但是,如说明所示,通常使用 QSignalMapper 会更好。或者以更面向对象的方式做事。

2) Second solution is to run a method defined in ButtonX class.

仔细查看您为第一个连接调用的最后一个参数键入的内容:

self.getButton(0, 0).buttonMethod()

上面将使用参数 0, 0 评估 getButton,然后在该对象上调用 buttonMethod 方法。因此,除非 buttonMethod 返回一个方法,否则您将使用 buttonMethod 的返回值作为连接调用的最后一个参数。如果这个方法返回一个函数,那么这就好了。

相反,我希望看到如下内容:

self.getButton(0, 0).buttonMethod # note no parenthesis at end

查看随 PyQt 提供的 PyQt 示例目录,因为它们将演示确切的语法并作为很好的示例。

这是一个小例子:

class MW(QMainWindow):
    def __init__(self, *args)
        QMainWindow.__init__(self, *args)
        layout = QHBoxLayout(self)
        self.b1 = QPushButton("Button1")
        self.b2 = QPushButton("Button2")
        layout.addWidget(self.b1)
        layout.addWidget(self.b2)
        self.connect(self.b1, SIGNAL("clicked()"), self.buttonWasPressed)
        self.connect(self.b2, SIGNAL("clicked()"), self.buttonWasPressed)

    def buttonWasPressed(self):
        print "button %s was pressed" % self.sender()

关于python - PyQT中事件的识别源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2917292/

相关文章:

python - 使用 csv.reader() 加载和访问数据时获取 AttributeError

user-interface - 如何在 Blackberry Storm 中设置抗锯齿?

javascript - Chrome 扩展用户界面

C++ Qt - 当类 T 的属性具有父级时的奇怪行为是 T

c++ - Qt 按钮调用 2 个插槽,我只需要一个

c++ - 如何让信号和槽在 Qt 中工作?

python - 在 Python 中,如何确定可迭代对象是否具有稳定的迭代顺序?

python - tensorflow 2.4.1 需要 6~=1.15.0,但是你有 6 个 1.16.0,这是不兼容的

python - 为什么我收到 AttributeError : 'module' object has no attribute 'set_trace'

python - PyQt6 在同一窗口中跨选项卡实现复制粘贴功能