I seem to be running into an issue where the modality of Qt dialogs is affecting the z-index
of other grandparents.
A minimal reproducible example is the following,
from PyQt6.QtCore import pyqtSignal, Qt
from PyQt6.QtWidgets import QApplication, QDialog, QLabel, QPushButton, QVBoxLayout
class DialogA(QDialog):
def __init__(self, parent):
super().__init__(parent)
self.setWindowModality(Qt.WindowModality.ApplicationModal)
self.setModal(True)
self.setWindowTitle("Dialog A")
self.setLayout(QVBoxLayout())
self.layout().addWidget(QLabel("This is Dialog A"))
open_dialog_b_button = QPushButton("Open Dialog B")
open_dialog_b_button.clicked.connect(self.open_dialog_b)
self.layout().addWidget(open_dialog_b_button)
def open_dialog_b(self):
dialog_b = DialogB(self)
dialog_b.closed.connect(self.close_dialog_a)
dialog_b.exec()
def close_dialog_a(self):
self.deleteLater()
class DialogB(QDialog):
closed = pyqtSignal()
def __init__(self, parent):
super().__init__(parent)
self.setWindowModality(Qt.WindowModality.ApplicationModal)
self.setModal(True)
self.setWindowTitle("Dialog B")
self.setLayout(QVBoxLayout())
self.layout().addWidget(QLabel("This is Dialog B"))
close_button = QPushButton("Close")
close_button.clicked.connect(self.on_close_button_clicked)
self.layout().addWidget(close_button)
def on_close_button_clicked(self):
self.closed.emit()
self.deleteLater()
def closeEvent(self, event):
self.closed.emit()
super().closeEvent(event)
if __name__ == "__main__":
app = QApplication([])
main_window = QDialog()
main_window.setWindowTitle("Main Window")
main_window.setLayout(QVBoxLayout())
open_dialog_a_button = QPushButton("Open Dialog A")
open_dialog_a_button.clicked.connect(lambda: DialogA(main_window).show())
main_window.layout().addWidget(open_dialog_a_button)
main_window.show()
app.exec()
Running the following code will create one MainWindow
dialog which creates DialogA
and DialogA
will create DialogB
. When DialogB
is closed via the button being closed, it seems to push the MainWindow
one window backwards. Therefore, any Window behind the MainWindow
will become infront of the MainWindow
. The last focused window seems to be important, as I am running PyCharm that is my last focused window. It is then easy to run via PyCharm and have PyCharm as my example window that comes into the foreground when closing DialogB
.
To reproduce it, run the code above and interact close DialogB
with the last focused window on the OS behind the MainWindow. When closing, the MainWindow will go behind the last focused window.
The structure here is mimicking the code structure in my much larger codebase, i.e. I need deleteLater
and have noticed that this is resolved using .close
instead.
My goal here is to understand, given the current code structure, why the MainWindow would be going behind the last focused window when closing DialogB
.
9