gpt4 book ai didi

python - PyQt4 QMessageBox中连接无法调用slot方法

转载 作者:行者123 更新时间:2023-12-01 09:13:02 24 4
gpt4 key购买 nike

我试图分析此处引用的示例代码:PyQt - QMessageBox这是片段:

from PyQt4.QtGui import *
from PyQt4.QtCore import *


class Window(QMainWindow):
def __init__(self):
super().__init__()

w = QWidget()
b = QPushButton(self)
b.setText("Show message!")

b.clicked.connect(self.showdialog)
w.setWindowTitle("PyQt Dialog demo")

def showdialog(self):
msg = QMessageBox()
msg.setIcon(QMessageBox.Question)


# self.connect(msg, SIGNAL('clicked()'), self.msgbtn)
msg.buttonClicked.connect(self.msgbtn)

msg.exec_()

def msgbtn(self, i):
print("Button pressed is:", i.text())



if __name__ == '__main__':
app = QApplication([])
w = Window()
w.show()
app.exec_()

在 PyQt 中将信号连接到槽有两种方法。对于按钮来说,它是:

QtCore.QObject.connect(button, QtCore.SIGNAL(“clicked()”), slot_function)

widget.clicked.connect(slot_function)

使用第二种方法效果很好:msgbtn 槽方法按预期调用。但是,如果我尝试将其更改为更常见的“PyQt-onic”连接方式(即第一个 - 我在代码片段中将其注释掉),则永远不会调用 slot 方法。有人可以帮我解决这个问题吗?

最佳答案

您传递给SIGNAL的信号不正确,QMessageBox没有点击信号,但信号是buttonClicked (QAbstractButton *)所以正确的是:

self.connect(msg, SIGNAL("buttonClicked(QAbstractButton *)"), self.msgbtn)

另一方面,这不是PyQt-onic风格,而是不建议使用的旧风格,但我们建议使用新风格。

旧样式:

self.connect(msg, SIGNAL("buttonClicked(QAbstractButton *)"), self.msgbtn)

新风格:

msg.buttonClicked.connect(self.msgbtn)

有关更多详细信息,请阅读 docs .

关于python - PyQt4 QMessageBox中连接无法调用slot方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51491372/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com