Issue
Hi, I'm trying to make simple GUI application using PyQt5, Python 3.4 and Windows 7.
Below code works properly.
# 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_())
Two windows are created. One is main window and the other is child window(popup window). But what I want is to make child window's default location is centered of main window.
So I've modified the code like this.
# 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_())
But this code makes problem. Child window doesn't show up. Only main window(=parent window) shows. In Qt's QDialog's manual, I found this.
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).
This is why I added the setParent().
What should I do?
Please help me!!
Solution
As specified in the documentation calling setParent
will just change the ownership of the QDialog
widget. If you want the QDialog
widget to be centered within it's parent, you need to pass the parent widget instance to the super constructor of your 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()
Answered By - Daniele Pantaleone
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.