PyQt QDialog 返回响应是“是”或“否”。

7

我有一个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
1个回答

6
您可以使用 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)

然而,在几乎所有只需要向用户呈现一条消息、通过点击按钮让他们做出选择或需要他们输入少量数据的情况下,我都可以使用普通对话框类上的内置静态方法——QMessageBoxQInputDialog

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接