Home > Software design >  Why dialog not show if I setParent?
Why dialog not show if I setParent?

Time:06-10

I create a dialog, and If I set mainwindow as it's parent, it not show.If I comment dlg.setParent(QApplication.activeWindow()),It work well, It's that dialog couldn't set mainwindows as it's parent?

from qtpy.QtWidgets import *
from qtpy.QtGui import *
from qtpy.QtCore import *

def center(w: QWidget):
    top = QApplication.activeWindow()

    rect = QRect(top.mapToGlobal(QPoint(0, 0)), top.size())
    r = QStyle.alignedRect(Qt.LeftToRight, Qt.AlignCenter, w.size(), rect)
    w.move(r.topLeft())

class Button(QPushButton):
    def mousePressEvent(self, e: QMouseEvent) -> None:
        super().mousePressEvent(e)
        dlg = QDialog()
        dlg.resize(100, 100)
        dlg.setParent(QApplication.activeWindow())
        # center(dlg)
        dlg.exec()

class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setCentralWidget(Button())

app = QApplication([])
main = MainWindow()
main.show()
app.exec()

CodePudding user response:

From the Qt documentation:

A dialog is always a top-level widget, 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). It will also share the parent's taskbar entry.

Use the overload of the QWidget::setParent() function to change the ownership of a QDialog widget. This function allows you to explicitly set the window flags of the reparented widget; using the overloaded function will clear the window flags specifying the window-system properties for the widget (in particular it will reset the Qt::Dialog flag).

The setParent method it takes two arguments, the second being the window flags, so leaving out the second argument leaves you with a qdialog with no window flag. In order do show the dialog again, just reassign the window flags.

  • Related