Child PyQt5 中不显示对话框

Child dialog doesn't show up in PyQt5


嗨,我正在尝试使用 PyQt5、Python 3.4 和 Windows 7 制作简单的 GUI 应用程序。

下面的代码可以正常工作。

# coding: utf-8

import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QDialog


class MainWnd(QMainWindow):
    def __init__(self):
        super().__init__()
        self.popup_dlg = None
        self.init_ui()

    def init_ui(self):
        self.setGeometry(100, 100, 300, 200)
        self.show()

        self.popup_dlg = ChildWnd()


class ChildWnd(QDialog):
    def __init__(self):
        super().__init__()
        self.init_ui()

    def init_ui(self):
        self.resize(200, 100)
        self.show()


if __name__ == "__main__":
    app = QApplication(sys.argv)
    mw = MainWnd()
    sys.exit(app.exec_())

创建了两个 windows。一个是main window,另一个是child window(popup window)。 但我想要的是让child window的默认位置以main window为中心。

所以我把代码修改成这样。

# coding: utf-8

import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QDialog


class MainWnd(QMainWindow):
    def __init__(self):
        super().__init__()
        self.popup_dlg = None
        self.init_ui()

    def init_ui(self):
        self.setGeometry(100, 100, 300, 200)
        self.show()

        self.popup_dlg = ChildWnd(self)  # make instance with parent window argument.


class ChildWnd(QDialog):

    def __init__(self, parent_wnd):
        super().__init__()
        self.setParent(parent_wnd)  # set child window's parent
        self.init_ui()

    def init_ui(self):
        self.resize(200, 100)
        self.show()


if __name__ == "__main__":
    app = QApplication(sys.argv)
    mw = MainWnd()
    sys.exit(app.exec_())

但是这段代码有问题。 Child window 没有出现。只有 main window(=parent window) 显示。在Qt的QDialog的手册中,我找到了这个。

but if it has a parent, its default location is centered on top of the parent's top-level widget (if it is not top-level itself).

这就是我添加 setParent().

的原因

我该怎么办?

请帮帮我!!

documentation 中所述,调用 setParent 只会更改 QDialog 小部件的所有权。如果您希望 QDialog 小部件在其父级中居中,则需要将父级小部件实例传递给 QDialog:

的超级构造函数
class ChildWnd(QDialog):

    def __init__(self, parent_wnd):
        super().__init__(parent_wnd)
        self.init_ui()

    def init_ui(self):
        self.resize(200, 100)
        self.show()