Monday, June 6, 2022

PyQt6: Open only one MDI Child Window at a time with subclassing

 This demo program shows how to create a custom event(close event for an MDI Child Window) by using the subclassing approach.

The output:



The code:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
import sys
from PyQt6.QtCore import *
from PyQt6.QtGui import *
from PyQt6.QtWidgets import *



sub_open = False


class MainW(QMainWindow):
    count = 0
    def __init__(self, parent=None):
        super(MainW, self).__init__(parent)
        self.mdi = QMdiArea()
        self.setCentralWidget(self.mdi)
        bar = self.menuBar()
        nsub = bar.addMenu("New")
        nsub.addAction("New")
        nsub.triggered[QAction].connect(self.waction)
        self.setWindowTitle("Post 40")

 
    #@f.pyqtSlot(str)
    def wclosed(self, text):
        global sub_open
        sub_open = False
        
        
    def waction(self, q):
        global sub_open
        if sub_open == True:
           return None
        sub_open = True   
        if q.text() == "New":
            MainW.count = MainW.count + 1
            sub = CustomSubWindow() # not QMdiSubWindow
            sub.setWidget(QTextEdit())
            #sub.setAttribute(Qt.WA_DeleteOnClose)
            sub.setWindowTitle("subwindow" + str(MainW.count))
            sub.subClosed.connect(self.wclosed)
            self.mdi.addSubWindow(sub)
            sub.show()

class CustomSubWindow(QMdiSubWindow):    
    subClosed = pyqtSignal(str)
    def closeEvent(self, event):
        self.subClosed.emit("")
        QMdiSubWindow.closeEvent(self, event)
        
        
def main():
   app = QApplication(sys.argv)
   ex = MainW()
   ex.show()
   sys.exit(app.exec())
    
if __name__ == '__main__':
   main()

No comments:

Post a Comment