简体   繁体   English

PyQt QDialog 返回响应是或否

[英]PyQt QDialog return response yes or no

I have a QDialog class我有一个 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")

I have a function which requires confirmation to continue or not, but with the current implementation it doesn't wait for QDialog to close.我有一个需要确认是否继续的函数,但在当前的实现中,它不会等待QDialog关闭。

How can I make my function wait for response from QDialog and then proceed accordingly.如何让我的函数等待QDialog响应,然后进行相应的处理。

I want to implement something similar to confirm function as shown below我想实现类似于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

You would use dialog.exec_() , which will open the dialog in a modal, blocking mode and returns an integer that indicates whether the dialog was accepted or not.您将使用dialog.exec_() ,它将以模态、阻塞模式打开对话框并返回一个整数,指示该对话框是否被接受。 Generally, instead of emitting signals, you probably just want to call self.accept() or self.reject() inside the dialog to close it.通常,您可能只想在对话框内调用self.accept()self.reject()来关闭它,而不是发出信号。

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

If I'm using a dialog to get a specific set of values from the user, I'll usually wrap it in a staticmethod , that way I can just call it and get values back within the control flow of my application, just like a normal function.如果我使用对话框从用户那里获取一组特定的值,我通常会将它包装在一个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)

However, in almost all cases where I just need to present a message to the user, or get them to make a choice by clicking a button, or I need them to input a small piece of data, I can use the built-in static methods on the normal dialog classes -- QMessageBox , QInputDialog然而,在几乎所有的情况下,我只需要向用户展示一条消息,或者通过点击按钮让他们做出选择,或者我需要他们输入一小段数据,我可以使用内置的静态普通对话框类上的方法—— QMessageBoxQInputDialog

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM