python - PyQt QDialog 返回响应是或否

标签 python pyqt

我有一个QDialog类

confirmation_dialog = uic.loadUiType("ui\\confirmation_dialog.ui")[0]

class ConfirmationDialog(QDialog,confirmation_dialog):

    def __init__(self,parent=None):
        QDialog.__init__(self,parent)
        self.setupUi(self)
        message = "Hello, Dialog test"
        self.yes_button.clicked.connect(self.yes_clicked)
        self.no_button.clicked.connect(self.no_clicked)
        self.message_box.insertPlainText(message)

    def yes_clicked(self):
        self.emit(SIGNAL("dialog_response"),"yes")

    def no_clicked(self):
        self.emit(SIGNAL("dialog_response"),"no")

我有一个函数需要确认是否继续,但在当前的实现中它不会等待 QDialog 关闭。

如何让我的函数等待 QDialog 的响应,然后进行相应的处理。

我想实现类似于 confirm 功能的东西,如下所示

def function(self):
    ....
    ....
    if self.confirm() == 'yes':
        #do something
    elif self.confirm() == 'no':
        #do something

def confirm(self):
    dialog = ConfirmationDialog()
    dialog.show()
    return #response from dialog

最佳答案

您可以使用 dialog.exec_(),它将以模态、阻塞模式打开对话框并返回一个整数,指示对话框是否被接受。通常,您可能只想在对话框内调用 self.accept()self.reject() 来关闭它,而不是发出信号。

dialog = ConfirmationDialog()
result = dialog.exec_()
if result:  # accepted
    return 'accepted'

如果我使用对话框从用户那里获取一组特定的值,我通常会将其包装在 staticmethod 中,这样我就可以调用它并在其中获取值我的应用程序的控制流,就像一个正常的功能。

class MyDialog(...)

    def getValues(self):
        return (self.textedit.text(), self.combobox.currentText())

    @staticmethod
    def launch(parent):
        dlg = MyDialog(parent)
        r = dlg.exec_()
        if r:
            return dlg.getValues()
        return None

values = MyDialog.launch(None)

然而,在几乎所有情况下,我只需要向用户显示一条消息,或者让他们通过单击按钮做出选择,或者我需要他们输入一小段数据,我都可以使用内置的-in 普通对话框类的静态方法 -- QMessageBox , QInputDialog

关于python - PyQt QDialog 返回响应是或否,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37411750/

相关文章:

python - 如何在不同类的 Main Widget 和 QObject 之间传递数据

python - 使用动态列表中的元素填充 QListWidget

python - 依赖管理 : subprocess32 needed for Python2. 7

python - ValueError : Error when checking : expected flatten_1_input to have shape (None, 4, 4, 512) 但得到形状为 (1, 150, 150, 3) 的数组

python - 如何通过 python/pyqt 创建 Windows 7 跳转列表?

python - 如何将抓取的项目放入 Pyqt5 小部件中?

python - Python requests 库新手,获取 '[Errno 61] Connection refused'

python - 使用 python multiprocessing 运行带有不同参数组合的循环脚本

python - 漂亮的 Python 打印机?

python - 在 GUI 记录器中添加颜色