喜露面,我試圖讓使用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_())
創建了兩個窗口。一個是主窗口,另一個是子窗口(彈出窗口)。 但我想要的是讓子窗口的默認位置居中主窗口。
所以我修改了這樣的代碼。
# 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_())
但是這段代碼會造成問題。子窗口不顯示。只有主窗口(=父窗口)顯示。在Qt的QDialog手冊中,我找到了這個。
,但如果它有一個父,其默認位置是在 父母的頂級窗口部件的頂部的中心位置(如果不是頂級本身)。
這就是爲什麼我添加了的setParent()。
我該怎麼辦?
請幫助我!
你嘗試通過父對象作爲參數的超級構造你的QDialog的? - > super().__ init __(parent_wnd) –
@Daniele Pantaleone,我將父對象添加到子窗口的super().__ init __()並刪除self.setParent()。有用!正是我想要的!感謝Daniele Pantaleone。你救了我整整一天XD – passion053
@Daniele Pantaleone,順便說一句,我想採納你的答案。但我不能接受評論。你能否重寫爲答案? – passion053