How to close a QDialog

时间:2015-06-30 19:26:58

标签: python qt user-interface pyqt qdialog

I've been trying to close a QDialog window that is branching off of my main window. The following have not worked for me so far:

self.close()
QDialog.close()

I tried other commands such as exit and exec_() with no luck. The most common error I get is

[className] object has no attribute 'close'

# Creating our window
class Ui_MainWindow(object):

    # Sets up GUI
    def setupUi(self, MainWindow):

        [GUI CODE]      

    # Sets text for parts of GUI
    def retranslateUi(self, MainWindow):

        [MORE GUI CODE]

    # Function handling screencap on click and metadata for filenames
    def cap_on_Click(arg1,arg2):

        popup = QDialog()
        popup_ui = Ui_Dialog()
        popup_ui.setupUi(popup)
        popup.show()
        sys.exit(popup.exec_())

The above is my main window

class Ui_Dialog(object):

    def setupUi(self, Dialog):

        [GUI CODE]

    def retranslateUi(self, Dialog):

        [MORE GUI CODE]

    def button_click(self, arg1):

        self.close()

The second block is the dialog window code. How do I close this dialog window?

3 个答案:

答案 0 :(得分:2)

首先,抱歉与C ++相关的链接,Python has the same concept

您可以尝试使用rejectacceptdone功能关闭对话框。通过这样做,您可以适当地设置返回值(RejectedAccepted或您指定的参数作为参数。

总而言之,您应该尝试拨打YourDialog.done(n)关闭对话框,并在您希望接受/拒绝时返回nYourDialog.accept()YourDialog.reject()

答案 1 :(得分:2)

我想问题是Ui_Dialog没有继承QDialog,因此未定义reject()accept()done()。我想

class Ui_Dialog(object):

应改为

class Ui_Dialog(QDialog):

但我无法测试它,因为没有提供最小的工作示例。

答案 2 :(得分:0)

由于QDialogQWidget,而QWidgetclose()方法,我不明白它是如何无效的。但是你永远不应该调用popup.exec_(),因为它会很高兴地要求你的很多代码在你没有意识到的情况下可以重入。这是不必要的 - 当cap_on_Click正在执行时,您已经运行了应用程序事件循环并且在调用堆栈上。

popup.show()之后,对话框将可见并可用,直到被用户接受或拒绝为止。希望您的对话框设计将按钮框的accepted()rejected()信号连接到对话框的accept()reject()位置。这是Qt Creator和Qt Designer提供的QDialog模板的默认行为,但您应该在查看Ui文件时进入信号/插槽编辑器模式进行检查。