如何从确认对话框中获取结果

How to get result from corfirmation dialog

我的弹出窗口结果有问题 window。下面我展示了我的部分代码来理解这个问题。

这是一种弹出窗口 window,用户可以在 GUI 中进行选择。在此之后它应该显示一个 window,其中会有问题 "Are you sure?",以及两个按钮 "Yes" 和 "No"。

问题是当我测试下面的代码时(msg.show() 之前和之后),我设置了与 False 相同的值。

为什么它不是这样工作的:

我该如何正确处理这个问题?还有其他方法吗?

from PyQt4 import QtCore, QtGui
from Message import Ui_Message
import sys

class MessageBox(QtGui.QDialog):
    def __init__(self, parent=None):
        QtGui.QWidget.__init__(self, parent=None)
        self.msg = Ui_Message()
        self.msg.setupUi(self)
        self.confirmed=False
        self.declined=False

        QtCore.QObject.connect(self.msg.NoButton, QtCore.SIGNAL(("clicked()")), self.Declined)
        QtCore.QObject.connect(self.msg.YesButton, QtCore.SIGNAL(("clicked()")), self.Confirmed)

    def Confirmed(self):
        self.confirmed = True
        MessageBox.close(self)
        return True

    def Declined(self):
        self.declined = True
        MessageBox.close(self)



if __name__ == "__main__":
    app = QtGui.QApplication(sys.argv)
    msg = MessageBox()
    print('Befor show window',msg.confirmed)
    msg.show()
    print('After show window', msg.confirmed)
    sys.exit(app.exec_())

您的示例不起作用,因为您正在 "After show window" window 关闭之前打印。阻塞的是 exec() 方法,而不是 show() 方法,因此您的示例需要这样写:

app = QtGui.QApplication(sys.argv)
msg = MessageBox()
print('Before show window', msg.confirmed)
msg.show()
app.exec_() # this blocks, waiting for close
print('After show window', msg.confirmed)
sys.exit()

但是,显示如何使用对话框来确认操作的更真实的示例如下所示:

import sys
from PyQt4 import QtCore, QtGui

class MessageBox(QtGui.QDialog):
    def __init__(self, parent=None):
        super(MessageBox, self).__init__(parent)
        self.yesButton = QtGui.QPushButton('Yes')
        self.noButton = QtGui.QPushButton('No')
        layout = QtGui.QGridLayout(self)
        layout.addWidget(QtGui.QLabel('Are you sure?'), 0, 0)
        layout.addWidget(self.yesButton, 1, 0)
        layout.addWidget(self.noButton, 1, 1)
        self.yesButton.clicked.connect(self.accept)
        self.noButton.clicked.connect(self.reject)

class Window(QtGui.QWidget):
    def __init__(self):
        super(Window, self).__init__()
        self.button = QtGui.QPushButton('Do Something')
        self.button.clicked.connect(self.handleButton)
        layout = QtGui.QVBoxLayout(self)
        layout.addWidget(self.button)

    def handleButton(self):
        if self.confirmSomething():
            print('Yes')
        else:
            print('No')

    def confirmSomething(self):
        msg = MessageBox(self)
        result = msg.exec_() == QtGui.QDialog.Accepted
        msg.deleteLater()
        return result

if __name__ == "__main__":

    app = QtGui.QApplication(sys.argv)
    window = Window()
    window.show()
    app.exec_()