You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PyQt中如何使用QMessageBox.open()并连接回调函数?

QMessageBox.open() 连接回调函数的解决方案

QMessageBox.open() 的参数要求:

  • receiver:必须是QObject子类的实例(比如窗口、自定义QObject对象)
  • member:该实例的方法名称字符串,Qt会根据方法的参数类型自动选择连接finished()或buttonClicked()信号(方法首参为指针则连buttonClicked(),否则连finished())

由于你的代码中button_clicked是局部函数,不属于任何QObject实例,需要通过以下方式处理:

方案1:使用自定义接收器对象包装回调

创建一个简单的QObject子类,将局部回调函数包装为其方法,满足open()的参数要求:

import sys
from PyQt6.QtWidgets import (
    QApplication, QMainWindow, QPushButton, QMessageBox
)
from PyQt6.QtCore import QObject

# 自定义接收器类,用于包装回调函数
class DialogReceiver(QObject):
    def __init__(self, callback, parent=None):
        super().__init__(parent)
        self.callback = callback
    
    # 定义匹配finished()信号的槽函数(参数为int类型返回码)
    def on_dialog_finished(self, result):
        self.callback()

def show_dialog(app, window):
   mbox = QMessageBox(window)
   mbox.setIcon(QMessageBox.Icon.Information)
   mbox.setText("Message box pop up window")
   mbox.setWindowTitle("QMessageBox Example")
   mbox.setStandardButtons(QMessageBox.StandardButton.Ok | QMessageBox.StandardButton.Cancel)
   def button_clicked():
       print("message box button clicked")
       mbox.done(0)
       app.quit()
   
   # 创建接收器实例并传入回调
   receiver = DialogReceiver(button_clicked)
   # 传入接收器对象和方法名称字符串
   mbox.open(receiver, "on_dialog_finished")

def main():
    app = QApplication(sys.argv)
    window = QMainWindow()
    window.resize(330, 200)
    window.setWindowTitle("Testing")
    button = QPushButton(window)
    button.setText("Button1")
    button.setGeometry(100,100,100,30)
    def button_clicked():
        print("button clicked")
        show_dialog(app, window)
    button.clicked.connect(button_clicked)
    window.show()
    app.exec()

if __name__ == '__main__':
    main()

方案2:直接连接信号(更简洁)

如果无需严格使用QMessageBox.open(),可以手动连接信号并显示对话框,这种方式更适配局部函数:

# 替换show_dialog中的open调用代码:
# mbox.open(receiver, member) 改为:
mbox.finished.connect(button_clicked)
mbox.show()

额外说明

如果需要获取用户点击的具体按钮,可以修改回调函数接收参数,此时Qt会自动匹配buttonClicked()信号:

def button_clicked(button):
    if button == QMessageBox.StandardButton.Ok:
        print("Ok按钮被点击")
    else:
        print("Cancel按钮被点击")
    mbox.done(0)
    app.quit()

内容的提问来源于stack exchange,提问作者Håkon Hægland

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.15 03:27:02