class mainwindow(QMainWindow): def __init__(self): super(mainwindow, self).__init__() # 主界面的布局 layout = QHBoxLayout() w = QWidget() w.setLayout(layout) self.setCentralWidget(w) # 显示弹出的子窗口 self.new_subwindow_btn = QPushButton("新建") layout.addWidget(self.new_subwindow_btn) self.new_subwindow_btn.clicked.connect(self.count) # 读取子窗口数据 self.read_content_btn = QPushButton("读取") layout.addWidget(self.read_content_btn) self.read_content_btn.clicked.connect(self.get_content) # 创建多文档区域 self.mdi = QMdiArea() layout.addWidget(self.mdi) # 要被创建的子窗口 self.w = QWidget() def count(self): # 使用 mdi 类来管理,判断当前窗口是否包含对象 # 如果不包含,创建。包含,不创建。 if self.mdi.currentSubWindow() == None: sub = QMdiSubWindow() # 每次 sub 页面关闭,都会销毁包含进来的对象 # 所以将包含的 半径、角度 等对象封装为一个类,或每次都新建 self.w = PopWindow() sub.setWidget(self.w.get_window()) sub.setWindowTitle("弹出窗口") # 如果不包含,弹出对话框可以浮动于任何位置,否则只能位于 mdi 区域内 self.mdi.addSubWindow(sub) sub.show() def get_content(self): if self.mdi.currentSubWindow() != None: angle, radis, dis = self.w.get_angle(), self.w.get_radis( ), self.w.get_dis() print(angle, radis, dis)
class MainWindow(QMainWindow): def __init__(self): super(MainWindow, self).__init__() self.mdiArea = QMdiArea() self.mdiArea.setHorizontalScrollBarPolicy(Qt.ScrollBarAsNeeded) self.mdiArea.setVerticalScrollBarPolicy(Qt.ScrollBarAsNeeded) self.setCentralWidget(self.mdiArea) self.mdiArea.subWindowActivated.connect(self.updateMenus) self.windowMapper = QSignalMapper(self) self.windowMapper.mapped[QWidget].connect(self.setActiveSubWindow) self.createActions() self.createMenus() self.createToolBars() self.createStatusBar() self.updateMenus() self.readSettings() self.setWindowTitle("MDI Test") def closeEvent(self, event): self.mdiArea.closeAllSubWindows() if self.mdiArea.currentSubWindow(): event.ignore() else: self.writeSettings() event.accept() def newFile(self): child = self.createMdiChild() child.newFile() child.show() def open(self): fileName, _ = QFileDialog.getOpenFileName(self) if fileName: existing = self.findMdiChild(fileName) if existing: self.mdiArea.setActiveSubWindow(existing) return child = self.createMdiChild() if child.loadFile(fileName): self.statusBar().showMessage("File loaded", 2000) child.show() else: child.close() def save(self): if self.activeMdiChild() and self.activeMdiChild().save(): self.statusBar().showMessage("File saved", 2000) def saveAs(self): if self.activeMdiChild() and self.activeMdiChild().saveAs(): self.statusBar().showMessage("File saved", 2000) def cut(self): if self.activeMdiChild(): self.activeMdiChild().cut() def copy(self): if self.activeMdiChild(): self.activeMdiChild().copy() def paste(self): if self.activeMdiChild(): self.activeMdiChild().paste() def about(self): QMessageBox.about( self, "About MDI", "The <b>MDI</b> example demonstrates how to write multiple " "document interface applications using Qt.") def updateMenus(self): hasMdiChild = (self.activeMdiChild() is not None) #self.saveAct.setEnabled(hasMdiChild) #self.saveAsAct.setEnabled(hasMdiChild) self.pasteAct.setEnabled(hasMdiChild) self.closeAct.setEnabled(hasMdiChild) self.closeAllAct.setEnabled(hasMdiChild) self.tileAct.setEnabled(hasMdiChild) self.cascadeAct.setEnabled(hasMdiChild) self.nextAct.setEnabled(hasMdiChild) self.previousAct.setEnabled(hasMdiChild) self.separatorAct.setVisible(hasMdiChild) hasSelection = (self.activeMdiChild() is not None and self.activeMdiChild().textCursor().hasSelection()) self.cutAct.setEnabled(hasSelection) self.copyAct.setEnabled(hasSelection) def updateWindowMenu(self): self.windowMenu.clear() self.windowMenu.addAction(self.closeAct) self.windowMenu.addAction(self.closeAllAct) self.windowMenu.addSeparator() self.windowMenu.addAction(self.tileAct) self.windowMenu.addAction(self.cascadeAct) self.windowMenu.addSeparator() self.windowMenu.addAction(self.nextAct) self.windowMenu.addAction(self.previousAct) self.windowMenu.addAction(self.separatorAct) windows = self.mdiArea.subWindowList() self.separatorAct.setVisible(len(windows) != 0) for i, window in enumerate(windows): child = window.widget() text = "%d %s" % (i + 1, child.userFriendlyCurrentFile()) if i < 9: text = '&' + text action = self.windowMenu.addAction(text) action.setCheckable(True) action.setChecked(child is self.activeMdiChild()) action.triggered.connect(self.windowMapper.map) self.windowMapper.setMapping(action, window) def createMdiChild(self): child = MdiChild() self.mdiArea.addSubWindow(child) child.copyAvailable.connect(self.cutAct.setEnabled) child.copyAvailable.connect(self.copyAct.setEnabled) return child # showntell def createMdiChild15(self): child = MdiChild_ShowNTell() self.mdiArea.addSubWindow(child) return child #MNIST def show_n_tell(self): print('show_n_tell....') child = self.createMdiChild15() print('self.createMdiChild15') #child.resize(830,480) #print('self.createMdiChild15') child.show print('child.show()') def createActions(self): self.cutAct = QAction( QIcon(':/images/cut.png'), "Cu&t", self, shortcut=QKeySequence.Cut, statusTip="Cut the current selection's contents to the clipboard", triggered=self.cut) self.copyAct = QAction( QIcon(':/images/copy.png'), "&Copy", self, shortcut=QKeySequence.Copy, statusTip="Copy the current selection's contents to the clipboard", triggered=self.copy) self.pasteAct = QAction( QIcon(':/images/paste.png'), "&Paste", self, shortcut=QKeySequence.Paste, statusTip= "Paste the clipboard's contents into the current selection", triggered=self.paste) self.closeAct = QAction("Cl&ose", self, statusTip="Close the active window", triggered=self.mdiArea.closeActiveSubWindow) self.closeAllAct = QAction("Close &All", self, statusTip="Close all the windows", triggered=self.mdiArea.closeAllSubWindows) self.tileAct = QAction("&Tile", self, statusTip="Tile the windows", triggered=self.mdiArea.tileSubWindows) self.cascadeAct = QAction("&Cascade", self, statusTip="Cascade the windows", triggered=self.mdiArea.cascadeSubWindows) self.nextAct = QAction("Ne&xt", self, shortcut=QKeySequence.NextChild, statusTip="Move the focus to the next window", triggered=self.mdiArea.activateNextSubWindow) self.previousAct = QAction( "Pre&vious", self, shortcut=QKeySequence.PreviousChild, statusTip="Move the focus to the previous window", triggered=self.mdiArea.activatePreviousSubWindow) self.separatorAct = QAction(self) self.separatorAct.setSeparator(True) # 메뉴 ACTION을 다이나믹하게 연결해준다 self.MenuActRef = { 'NewFileAct': 0, 'OpnFileAct': 0, 'SavFileAct': 0, 'SavASFileAct': 0, 'AboutAct': 0, 'AboutQTAct': 0, 'ExitAct': 0, 'SwitchLayout': 0, 'ShowNTell': 0 } # ******* Create the File Menu ******* self.NewFileAct = QAction(QIcon(':/images/new.png'), '&New File', self) self.NewFileAct.setShortcut("Ctrl+N") self.NewFileAct.setStatusTip('Create a New File') self.NewFileAct.triggered.connect(self.newFile) self.MenuActRef['NewFileAct'] = self.NewFileAct #self.newAct = QAction(QIcon(':/images/new.png'), "&New", self, # shortcut=QKeySequence.New, statusTip="Create a new file", # triggered=self.newFile) # ******* Open File Menu Items ******* self.OpnFileAct = QAction(QIcon(':/images/open.png'), '&Open File', self) self.OpnFileAct.setShortcut("Ctrl+O") self.OpnFileAct.setStatusTip('Open an Existing File') self.OpnFileAct.triggered.connect(self.open) self.MenuActRef['OpnFileAct'] = self.OpnFileAct #self.openAct = QAction(QIcon(':/images/open.png'), "&Open...", self, # shortcut=QKeySequence.Open, statusTip="Open an existing file", # triggered=self.open) # ******* Save File Menu Items ******* self.SavFileAct = QAction(QIcon(':/images/save.png'), '&Save File', self) self.SavFileAct.setShortcut("Ctrl+S") self.SavFileAct.setStatusTip('Save Current File') self.SavFileAct.triggered.connect(self.save) self.MenuActRef['SavFileAct'] = self.SavFileAct #self.saveAct = QAction(QIcon(':/images/save.png'), "&Save", self, # shortcut=QKeySequence.Save, # statusTip="Save the document to disk", triggered=self.save) # ******* SaveAS File Menu Items ******* self.SavASFileAct = QAction('Save &As File', self) self.SavASFileAct.setShortcut("Ctrl+A") self.SavASFileAct.setStatusTip('Save Current File under a new name ') self.SavASFileAct.triggered.connect(self.saveAs) self.MenuActRef['SavASFileAct'] = self.SavASFileAct #self.saveAsAct = QAction("Save &As...", self, # shortcut=QKeySequence.SaveAs, # statusTip="Save the document under a new name", # triggered=self.saveAs) # ******* About Menu Items ******* self.aboutAct = QAction("&About", self) self.aboutAct.setStatusTip("Show the application's About box") self.aboutAct.triggered.connect(self.about) self.MenuActRef['AboutAct'] = self.aboutAct # ******* About QT Menu Items ******* self.aboutAct = QAction("About &Qt", self) self.aboutAct.setStatusTip("Show the Qt library's About box") self.aboutAct.triggered.connect(QApplication.instance().aboutQt) self.MenuActRef['AboutQTAct'] = self.aboutAct # ******* Exit Menu Items ******* self.exitAct = QAction("E&xit", self) self.exitAct.setStatusTip("Exit the application") self.exitAct.triggered.connect(QApplication.instance().closeAllWindows) self.MenuActRef['ExitAct'] = self.exitAct #self.exitAct = QAction("E&xit", self, shortcut=QKeySequence.Quit, # statusTip="Exit the application", # triggered=QApplication.instance().closeAllWindows) # ******* Switch layout Items ******* self.SwitchLayout = QAction("&Switch layout direction", self) self.SwitchLayout.setStatusTip("Switch layout direction") self.SwitchLayout.triggered.connect(self.switchLayoutDirection) self.MenuActRef['SwitchLayout'] = self.SwitchLayout #self.SwitchLayout = QAction("&Switch layout direction", self, # statusTip="Switch layout direction", # triggered=self.switchLayoutDirection) # ******* Switch layout Items ******* self.ShowNTell = QAction("&ShowNTell", self) self.ShowNTell.setStatusTip("&ShowNTell") self.ShowNTell.triggered.connect(self.show_n_tell) self.MenuActRef['ShowNTell'] = self.ShowNTell #self.ShowNTell = QAction("&show_n_tell", self, # statusTip="show_n_tell", # triggered=self.show_n_tell) def createMenus(self): # 메뉴를 다이나믹하게 생성하고 연결함 self.MenuLayout = { 0: { 'addMenu': '&File', 'addToolMenu': 'File' }, 1: { 'addDynamic': 'NewFileAct', 'addToolbar': 'NewFileAct' }, 2: { 'addDynamic': 'OpnFileAct', 'addToolbar': 'OpnFileAct' }, 3: { 'addDynamic': 'SavFileAct', 'addToolbar': 'SavFileAct' }, 4: { 'addDynamic': 'SavASFileAct' }, 5: { 'addSeparator': '' }, 6: { 'addDynamic': 'SwitchLayout' }, 7: { 'addDynamic': 'ExitAct' }, 8: { 'addMenu': '&Edit' }, 9: { 'addAction': self.cutAct }, 10: { 'addAction': self.copyAct }, 11: { 'addAction': self.pasteAct }, 12: { 'addMenu': '&Window' }, 13: { 'updateMenu': '' }, 14: { 'addSeparator': '' }, 15: { 'addMenu': '&Help' }, 16: { 'addDynamic': 'AboutAct' }, 17: { 'addDynamic': 'AboutQTAct' }, 18: { 'addMenu': '&MNIST' }, 19: { 'addDynamic': 'ShowNTell' } } for idx in self.MenuLayout: item = self.MenuLayout[idx] if 'addMenu' in item.keys(): self.windowMenu = self.menuBar().addMenu(item['addMenu']) elif 'addAction' in item.keys(): self.windowMenu.addAction(item['addAction']) elif 'addSeparator' in item.keys(): self.windowMenu.addSeparator() elif 'updateMenu' in item.keys(): self.updateWindowMenu() self.windowMenu.aboutToShow.connect(self.updateWindowMenu) # 메뉴 ACTION을 다이나믹하게 elif 'addDynamic' in item.keys(): self.windowMenu.addAction(self.MenuActRef[item['addDynamic']]) def createToolBars(self): for idx in self.MenuLayout: item = self.MenuLayout[idx] if 'addToolMenu' in item.keys(): self.fileToolBar = self.addToolBar(item['addToolMenu']) elif 'addToolbar' in item.keys(): self.fileToolBar.addAction(self.MenuActRef[item['addDynamic']]) #self.fileToolBar = self.addToolBar("File") #self.fileToolBar.addAction(self.MenuActRef['NewFileAct']) #self.fileToolBar.addAction(self.MenuActRef['OpnFileAct']) #self.fileToolBar.addAction(self.MenuActRef['SavFileAct']) #self.fileToolBar.addAction(self.newAct) #self.fileToolBar.addAction(self.openAct) #self.fileToolBar.addAction(self.saveAct) self.editToolBar = self.addToolBar("Edit") self.editToolBar.addAction(self.cutAct) self.editToolBar.addAction(self.copyAct) self.editToolBar.addAction(self.pasteAct) def createStatusBar(self): self.statusBar().showMessage("Ready") def readSettings(self): settings = QSettings('NH-Soft', 'MDI Example') pos = settings.value('pos', QPoint(200, 200)) size = settings.value('size', QSize(400, 400)) self.move(pos) self.resize(size) def writeSettings(self): settings = QSettings('NH-Soft', 'MDI Example') settings.setValue('pos', self.pos()) settings.setValue('size', self.size()) def activeMdiChild(self): activeSubWindow = self.mdiArea.activeSubWindow() if activeSubWindow: return activeSubWindow.widget() return None def findMdiChild(self, fileName): canonicalFilePath = QFileInfo(fileName).canonicalFilePath() for window in self.mdiArea.subWindowList(): if window.widget().currentFile() == canonicalFilePath: return window return None def switchLayoutDirection(self): if self.layoutDirection() == Qt.LeftToRight: QApplication.setLayoutDirection(Qt.RightToLeft) else: QApplication.setLayoutDirection(Qt.LeftToRight) def setActiveSubWindow(self, window): if window: self.mdiArea.setActiveSubWindow(window)
class appWindow(QMainWindow): """ Application entry point, subclasses QMainWindow and implements the main widget, sets necessary window behaviour etc. """ def __init__(self, parent=None): super(appWindow, self).__init__(parent) #create the menu bar self.createMenuBar() self.mdi = QMdiArea(self) #create area for files to be displayed self.mdi.setObjectName('mdi area') #create toolbar and add the toolbar plus mdi to layout self.createToolbar() #set flags so that window doesnt look weird self.mdi.setOption(QMdiArea.DontMaximizeSubWindowOnActivation, True) self.mdi.setTabsClosable(True) self.mdi.setTabsMovable(True) self.mdi.setDocumentMode(False) #declare main window layout self.setCentralWidget(self.mdi) # self.resize(1280, 720) #set collapse dim self.mdi.subWindowActivated.connect(self.tabSwitched) self.readSettings() def createMenuBar(self): # Fetches a reference to the menu bar in the main window, and adds actions to it. titleMenu = self.menuBar() #fetch reference to current menu bar self.menuFile = titleMenu.addMenu('File') #File Menu newAction = self.menuFile.addAction("New", self.newProject) openAction = self.menuFile.addAction("Open", self.openProject) saveAction = self.menuFile.addAction("Save", self.saveProject) newAction.setShortcut(QKeySequence.New) openAction.setShortcut(QKeySequence.Open) saveAction.setShortcut(QKeySequence.Save) self.menuEdit = titleMenu.addMenu('Edit') undoAction = self.undo = self.menuEdit.addAction( "Undo", lambda x=self: x.activeScene.painter.undoAction.trigger()) redoAction = self.redo = self.menuEdit.addAction( "Redo", lambda x=self: x.activeScene.painter.redoAction.trigger()) undoAction.setShortcut(QKeySequence.Undo) redoAction.setShortcut(QKeySequence.Redo) self.menuEdit.addAction( "Show Undo Stack", lambda x=self: x.activeScene.painter.createUndoView(self)) self.menuEdit.addSeparator() self.menuEdit.addAction("Add new symbols", self.addSymbolWindow) self.menuGenerate = titleMenu.addMenu('Generate') #Generate menu imageAction = self.menuGenerate.addAction("Image", self.saveImage) reportAction = self.menuGenerate.addAction("Report", self.generateReport) imageAction.setShortcut(QKeySequence("Ctrl+P")) reportAction.setShortcut(QKeySequence("Ctrl+R")) def createToolbar(self): #place holder for toolbar with fixed width, layout may change self.toolbar = toolbar(self) self.toolbar.setObjectName("Toolbar") # self.addToolBar(Qt.LeftToolBarArea, self.toolbar) self.addDockWidget(Qt.LeftDockWidgetArea, self.toolbar) self.toolbar.toolbuttonClicked.connect(self.toolButtonClicked) self.toolbar.populateToolbar() def toolButtonClicked(self, object): # To add the corresponding symbol for the clicked button to active scene. if self.mdi.currentSubWindow(): currentDiagram = self.mdi.currentSubWindow().tabber.currentWidget( ).painter if currentDiagram: graphic = getattr(shapes, object['object'])(*map( lambda x: int(x) if x.isdigit() else x, object['args'])) graphic.setPos(50, 50) currentDiagram.addItemPlus(graphic) def addSymbolWindow(self): # Opens the add symbol window when requested from utils.custom import ShapeDialog ShapeDialog(self).exec() def newProject(self): #call to create a new file inside mdi area project = FileWindow(self.mdi) project.setObjectName("New Project") self.mdi.addSubWindow(project) if not project.tabList: # important when unpickling a file instead project.newDiagram() #create a new tab in the new file project.fileCloseEvent.connect( self.fileClosed) #closed file signal to switch to sub window view if self.count > 1: #switch to tab view if needed self.mdi.setViewMode(QMdiArea.TabbedView) project.show() def openProject(self): #show the open file dialog to open a saved file, then unpickle it. name = QFileDialog.getOpenFileNames(self, 'Open File(s)', '', 'Process Flow Diagram (*pfd)') if name: for files in name[0]: with open(files, 'r') as file: projectData = load(file) project = FileWindow(self.mdi) self.mdi.addSubWindow(project) #create blank window and set its state project.__setstate__(projectData) project.resizeHandler() project.fileCloseEvent.connect(self.fileClosed) project.show() if self.count > 1: # self.tabSpace.setVisible(True) self.mdi.setViewMode(QMdiArea.TabbedView) def saveProject(self): #serialize all files in mdi area for j, i in enumerate(self.activeFiles ): #get list of all windows with atleast one tab if i.tabCount: name = QFileDialog.getSaveFileName( self, 'Save File', f'New Diagram {j}', 'Process Flow Diagram (*.pfd)') i.saveProject(name) else: return False return True def saveImage(self): #place holder for future implementaion pass def generateReport(self): #place holder for future implementaion pass def tabSwitched(self, window): #handle window switched edge case if window and window.tabCount: window.resizeHandler() def resizeEvent(self, event): #overload resize to also handle resize on file windows inside for i in self.mdi.subWindowList(): i.resizeHandler() self.toolbar.resize() super(appWindow, self).resizeEvent(event) def closeEvent(self, event): #save alert on window close if len(self.activeFiles) and not dialogs.saveEvent(self): event.ignore() else: event.accept() self.writeSettings() def fileClosed(self, index): #checks if the file tab menu needs to be removed if self.count <= 2: self.mdi.setViewMode(QMdiArea.SubWindowView) def writeSettings(self): # write window state on window close settings.beginGroup("MainWindow") settings.setValue("maximized", self.isMaximized()) if not self.isMaximized(): settings.setValue("size", self.size()) settings.setValue("pos", self.pos()) settings.endGroup() def readSettings(self): # read window state when app launches settings.beginGroup("MainWindow") self.resize(settings.value("size", QSize(1280, 720))) self.move(settings.value("pos", QPoint(320, 124))) if settings.value("maximized", False, type=bool): self.showMaximized() settings.endGroup() #useful one liner properties for getting data @property def activeFiles(self): return [i for i in self.mdi.subWindowList() if i.tabCount] @property def count(self): return len(self.mdi.subWindowList()) @property def activeScene(self): return self.mdi.currentSubWindow().tabber.currentWidget() #Key input handler def keyPressEvent(self, event): #overload key press event for custom keyboard shortcuts if event.modifiers() & Qt.ControlModifier: if event.key() == Qt.Key_A: #todo implement selectAll for item in self.mdi.activeSubWindow().tabber.currentWidget( ).items: item.setSelected(True) #todo copy, paste, undo redo else: return event.accept() elif event.key() == Qt.Key_Q: if self.mdi.activeSubWindow() and self.mdi.activeSubWindow( ).tabber.currentWidget(): for item in self.mdi.activeSubWindow().tabber.currentWidget( ).painter.selectedItems(): item.rotation -= 1 elif event.key() == Qt.Key_E: if self.mdi.activeSubWindow() and self.mdi.activeSubWindow( ).tabber.currentWidget(): for item in self.mdi.activeSubWindow().tabber.currentWidget( ).painter.selectedItems(): item.rotation += 1
class MainWindow(QMainWindow): """This create the main window of the application""" def __init__(self): super(MainWindow, self).__init__() # remove close & maximize window buttons #self.setWindowFlags(Qt.CustomizeWindowHint|Qt.WindowMinimizeButtonHint) self.setMinimumSize(500, 666) #self.setMaximumSize(1000,666) self.mdiArea = QMdiArea() self.mdiArea.setHorizontalScrollBarPolicy(Qt.ScrollBarAsNeeded) self.mdiArea.setVerticalScrollBarPolicy(Qt.ScrollBarAsNeeded) self.setCentralWidget(self.mdiArea) self.mdiArea.subWindowActivated.connect(self.updateMenus) self.mdiArea.setViewMode(QMdiArea.TabbedView) self.windowMapper = QSignalMapper(self) self.windowMapper.mapped[QWidget].connect(self.setActiveSubWindow) self.child = None self.createActions() self.createMenus() self.createStatusBar() self.updateMenus() self.readSettings() self.setWindowTitle("LEKTURE") mytoolbar = QToolBar() #self.toolbar = self.addToolBar() mytoolbar.addAction(self.newAct) mytoolbar.addAction(self.openAct) mytoolbar.addAction(self.saveAct) mytoolbar.addAction(self.saveAsAct) mytoolbar.addSeparator() mytoolbar.addAction(self.outputsAct) mytoolbar.addAction(self.scenarioAct) self.scenarioAct.setVisible(False) mytoolbar.setMovable(False) mytoolbar.setFixedWidth(60) self.addToolBar(Qt.LeftToolBarArea, mytoolbar) def closeEvent(self, scenario): """method called when the main window wants to be closed""" self.mdiArea.closeAllSubWindows() if self.mdiArea.currentSubWindow(): scenario.ignore() else: self.writeSettings() scenario.accept() def newFile(self): """creates a new project""" child = self.createProjekt() child.newFile() child.show() self.child = child def open(self): """open a project""" fileName, _ = QFileDialog.getOpenFileName(self) if fileName: existing = self.findProjekt(fileName) if existing: self.mdiArea.setActiveSubWindow(existing) return child = self.createProjekt() if child.loadFile(fileName): self.statusBar().showMessage("File loaded", 2000) child.show() else: child.close() def save(self): """called when user save a project""" if self.activeProjekt() and self.activeProjekt().save(): self.statusBar().showMessage("File saved", 2000) else: self.statusBar().showMessage("Error when trying to save the file") def saveAs(self): """called when user save AS a project""" if self.activeProjekt() and self.activeProjekt().saveAs(): self.statusBar().showMessage("File saved", 2000) else: self.statusBar().showMessage("Error when trying to save the file") def openFolder(self): """called when user calls 'reveal in finder' function""" if self.activeProjekt() and self.activeProjekt().openFolder(): self.statusBar().showMessage("File revealed in Finder", 2000) def about(self): """called when user wants to know a bit more on the app""" import sys python_version = str(sys.version_info[0]) python_version_temp = sys.version_info[1:5] for item in python_version_temp: python_version = python_version + "." + str(item) QMessageBox.about(self, "About Lekture", "pylekture build " + str(pylekture.__version__ + "\n" + \ "python version " + str(python_version))) def updateMenus(self): """update menus""" hasProjekt = (self.activeProjekt() is not None) self.saveAct.setEnabled(hasProjekt) self.saveAsAct.setEnabled(hasProjekt) self.outputsAct.setEnabled(hasProjekt) self.scenarioAct.setEnabled(hasProjekt) self.openFolderAct.setEnabled(hasProjekt) self.closeAct.setEnabled(hasProjekt) self.closeAllAct.setEnabled(hasProjekt) self.nextAct.setEnabled(hasProjekt) self.previousAct.setEnabled(hasProjekt) self.separatorAct.setVisible(hasProjekt) def updateWindowMenu(self): """unpates menus on the window toolbar""" self.windowMenu.clear() self.windowMenu.addAction(self.closeAct) self.windowMenu.addAction(self.closeAllAct) self.windowMenu.addSeparator() self.windowMenu.addAction(self.nextAct) self.windowMenu.addAction(self.previousAct) self.windowMenu.addAction(self.separatorAct) windows = self.mdiArea.subWindowList() self.separatorAct.setVisible(len(windows) != 0) for i, window in enumerate(windows): child = window.widget() text = "%d %s" % (i + 1, child.userFriendlyCurrentFile()) if i < 9: text = '&' + text action = self.windowMenu.addAction(text) action.setCheckable(True) action.setChecked(child is self.activeProjekt()) action.triggered.connect(self.windowMapper.map) self.windowMapper.setMapping(action, window) def createProjekt(self): """create a new project""" child = Projekt() self.mdiArea.addSubWindow(child) self.child = child return child def createActions(self): """create all actions""" self.newAct = QAction("&New", self, shortcut=QKeySequence.New, statusTip="Create a new file", triggered=self.newFile) self.openAct = QAction("&Open...", self, shortcut=QKeySequence.Open, statusTip="Open an existing file", triggered=self.open) self.saveAct = QAction("&Save", self, shortcut=QKeySequence.Save, statusTip="Save the document to disk", triggered=self.save) self.saveAsAct = QAction("Save &As...", self, shortcut=QKeySequence.SaveAs, statusTip="Save the document under a new name", triggered=self.saveAs) self.openFolderAct = QAction("Open Project Folder", self, statusTip="Reveal Project in Finder", triggered=self.openFolder) self.exitAct = QAction("E&xit", self, shortcut=QKeySequence.Quit, statusTip="Exit the application", triggered=QApplication.instance().closeAllWindows) self.closeAct = QAction("Cl&ose", self, statusTip="Close the active window", triggered=self.mdiArea.closeActiveSubWindow) self.outputsAct = QAction("Outputs", self, statusTip="Open the outputs panel", triggered=self.openOutputsPanel) self.scenarioAct = QAction("Scenario", self, statusTip="Open the scenario panel", triggered=self.openScenarioPanel) self.closeAllAct = QAction("Close &All", self, statusTip="Close all the windows", triggered=self.mdiArea.closeAllSubWindows) self.nextAct = QAction("Ne&xt", self, shortcut=QKeySequence.NextChild, statusTip="Move the focus to the next window", triggered=self.mdiArea.activateNextSubWindow) self.previousAct = QAction("Pre&vious", self, shortcut=QKeySequence.PreviousChild, statusTip="Move the focus to the previous window", triggered=self.mdiArea.activatePreviousSubWindow) self.separatorAct = QAction(self) self.separatorAct.setSeparator(True) self.aboutAct = QAction("&About", self, statusTip="Show the application's About box", triggered=self.about) def createMenus(self): """create all menus""" self.fileMenu = self.menuBar().addMenu("&File") self.fileMenu.addAction(self.newAct) self.fileMenu.addAction(self.openAct) self.fileMenu.addAction(self.saveAct) self.fileMenu.addAction(self.saveAsAct) self.fileMenu.addSeparator() self.fileMenu.addAction(self.openFolderAct) self.fileMenu.addAction(self.exitAct) self.viewMenu = self.menuBar().addMenu("&View") self.viewMenu.addAction(self.outputsAct) self.viewMenu.addAction(self.scenarioAct) self.windowMenu = self.menuBar().addMenu("&Window") self.updateWindowMenu() self.windowMenu.aboutToShow.connect(self.updateWindowMenu) self.menuBar().addSeparator() self.helpMenu = self.menuBar().addMenu("&Help") self.helpMenu.addAction(self.aboutAct) def createStatusBar(self): """create the status bar""" self.statusBar().showMessage("Ready") def readSettings(self): """read the settings""" settings = QSettings('Pixel Stereo', 'lekture') pos = settings.value('pos', QPoint(200, 200)) size = settings.value('size', QSize(1000, 650)) self.move(pos) self.resize(size) def writeSettings(self): """write settings""" settings = QSettings('Pixel Stereo', 'lekture') settings.setValue('pos', self.pos()) settings.setValue('size', self.size()) def activeProjekt(self): """return the active project object""" activeSubWindow = self.mdiArea.activeSubWindow() if activeSubWindow: return activeSubWindow.widget() else: return None def findProjekt(self, fileName): """return the project""" canonicalFilePath = QFileInfo(fileName).canonicalFilePath() for window in self.mdiArea.subWindowList(): if window.widget().currentFile() == canonicalFilePath: return window return None def setActiveSubWindow(self, window): """set the active sub window""" if window: self.mdiArea.setActiveSubWindow(window) def openOutputsPanel(self): """switch to the outputs editor""" if self.child: project = self.activeProjekt() project.scenario_events_group.setVisible(False) project.outputs_group.setVisible(True) self.scenarioAct.setVisible(True) self.outputsAct.setVisible(False) def openScenarioPanel(self): """switch to the scenario editors""" if self.child: project = self.activeProjekt() project.outputs_group.setVisible(False) project.scenario_events_group.setVisible(True) self.scenarioAct.setVisible(False) self.outputsAct.setVisible(True)
class MainWindow(QMainWindow): def __init__(self): super(MainWindow, self).__init__() self.mdiArea = QMdiArea() self.mdiArea.setHorizontalScrollBarPolicy(Qt.ScrollBarAsNeeded) self.mdiArea.setVerticalScrollBarPolicy(Qt.ScrollBarAsNeeded) self.setCentralWidget(self.mdiArea) self.mdiArea.subWindowActivated.connect(self.updateMenus) self.windowMapper = QSignalMapper(self) self.windowMapper.mapped[QWidget].connect(self.setActiveSubWindow) self.createActions() self.createMenus() self.createToolBars() self.createStatusBar() self.updateMenus() self.readSettings() self.setWindowTitle("MDI") def closeEvent(self, event): self.mdiArea.closeAllSubWindows() if self.mdiArea.currentSubWindow(): event.ignore() else: self.writeSettings() event.accept() def newFile(self): child = self.createMdiChild() child.newFile() child.show() def open(self): fileName, _ = QFileDialog.getOpenFileName(self) if fileName: existing = self.findMdiChild(fileName) if existing: self.mdiArea.setActiveSubWindow(existing) return child = self.createMdiChild() if child.loadFile(fileName): self.statusBar().showMessage("File loaded", 2000) child.show() else: child.close() def save(self): if self.activeMdiChild() and self.activeMdiChild().save(): self.statusBar().showMessage("File saved", 2000) def saveAs(self): if self.activeMdiChild() and self.activeMdiChild().saveAs(): self.statusBar().showMessage("File saved", 2000) def cut(self): if self.activeMdiChild(): self.activeMdiChild().cut() def copy(self): if self.activeMdiChild(): self.activeMdiChild().copy() def paste(self): if self.activeMdiChild(): self.activeMdiChild().paste() def about(self): QMessageBox.about( self, "About MDI", "The <b>MDI</b> example demonstrates how to write multiple " "document interface applications using Qt.") def updateMenus(self): hasMdiChild = (self.activeMdiChild() is not None) self.saveAct.setEnabled(hasMdiChild) self.saveAsAct.setEnabled(hasMdiChild) self.pasteAct.setEnabled(hasMdiChild) self.closeAct.setEnabled(hasMdiChild) self.closeAllAct.setEnabled(hasMdiChild) self.tileAct.setEnabled(hasMdiChild) self.cascadeAct.setEnabled(hasMdiChild) self.nextAct.setEnabled(hasMdiChild) self.previousAct.setEnabled(hasMdiChild) self.separatorAct.setVisible(hasMdiChild) hasSelection = (self.activeMdiChild() is not None and self.activeMdiChild().textCursor().hasSelection()) self.cutAct.setEnabled(hasSelection) self.copyAct.setEnabled(hasSelection) def updateWindowMenu(self): self.windowMenu.clear() self.windowMenu.addAction(self.closeAct) self.windowMenu.addAction(self.closeAllAct) self.windowMenu.addSeparator() self.windowMenu.addAction(self.tileAct) self.windowMenu.addAction(self.cascadeAct) self.windowMenu.addSeparator() self.windowMenu.addAction(self.nextAct) self.windowMenu.addAction(self.previousAct) self.windowMenu.addAction(self.separatorAct) windows = self.mdiArea.subWindowList() self.separatorAct.setVisible(len(windows) != 0) for i, window in enumerate(windows): child = window.widget() text = "%d %s" % (i + 1, child.userFriendlyCurrentFile()) if i < 9: text = '&' + text action = self.windowMenu.addAction(text) action.setCheckable(True) action.setChecked(child is self.activeMdiChild()) action.triggered.connect(self.windowMapper.map) self.windowMapper.setMapping(action, window) def createMdiChild(self): child = MdiChild() self.mdiArea.addSubWindow(child) child.copyAvailable.connect(self.cutAct.setEnabled) child.copyAvailable.connect(self.copyAct.setEnabled) return child def createActions(self): self.newAct = QAction(QIcon(':/images/new.png'), "&New", self, shortcut=QKeySequence.New, statusTip="Create a new file", triggered=self.newFile) self.openAct = QAction(QIcon(':/images/open.png'), "&Open...", self, shortcut=QKeySequence.Open, statusTip="Open an existing file", triggered=self.open) self.saveAct = QAction(QIcon(':/images/save.png'), "&Save", self, shortcut=QKeySequence.Save, statusTip="Save the document to disk", triggered=self.save) self.saveAsAct = QAction( "Save &As...", self, shortcut=QKeySequence.SaveAs, statusTip="Save the document under a new name", triggered=self.saveAs) self.exitAct = QAction( "E&xit", self, shortcut=QKeySequence.Quit, statusTip="Exit the application", triggered=QApplication.instance().closeAllWindows) self.cutAct = QAction( QIcon(':/images/cut.png'), "Cu&t", self, shortcut=QKeySequence.Cut, statusTip="Cut the current selection's contents to the clipboard", triggered=self.cut) self.suggestAct = QAction( "Suggest", self, shortcut=QKeySequence.Copy, statusTip="Cut the current selection's contents to the clipboard", triggered=self.copy) self.copyAct = QAction( QIcon(':/images/copy.png'), "&Copy", self, shortcut=QKeySequence.Copy, statusTip="Copy the current selection's contents to the clipboard", triggered=self.copy) self.pasteAct = QAction( QIcon(':/images/paste.png'), "&Paste", self, shortcut=QKeySequence.Paste, statusTip= "Paste the clipboard's contents into the current selection", triggered=self.paste) self.closeAct = QAction("Cl&ose", self, statusTip="Close the active window", triggered=self.mdiArea.closeActiveSubWindow) self.closeAllAct = QAction("Close &All", self, statusTip="Close all the windows", triggered=self.mdiArea.closeAllSubWindows) self.tileAct = QAction("&Tile", self, statusTip="Tile the windows", triggered=self.mdiArea.tileSubWindows) self.cascadeAct = QAction("&Cascade", self, statusTip="Cascade the windows", triggered=self.mdiArea.cascadeSubWindows) self.nextAct = QAction("Ne&xt", self, shortcut=QKeySequence.NextChild, statusTip="Move the focus to the next window", triggered=self.mdiArea.activateNextSubWindow) self.previousAct = QAction( "Pre&vious", self, shortcut=QKeySequence.PreviousChild, statusTip="Move the focus to the previous window", triggered=self.mdiArea.activatePreviousSubWindow) self.separatorAct = QAction(self) self.separatorAct.setSeparator(True) self.aboutAct = QAction("&About", self, statusTip="Show the application's About box", triggered=self.about) self.aboutQtAct = QAction("About &Qt", self, statusTip="Show the Qt library's About box", triggered=QApplication.instance().aboutQt) def createMenus(self): self.fileMenu = self.menuBar().addMenu("&File") self.fileMenu.addAction(self.newAct) self.fileMenu.addAction(self.openAct) self.fileMenu.addAction(self.saveAct) self.fileMenu.addAction(self.saveAsAct) self.fileMenu.addSeparator() action = self.fileMenu.addAction("Switch layout direction") action.triggered.connect(self.switchLayoutDirection) self.fileMenu.addAction(self.exitAct) self.editMenu = self.menuBar().addMenu("&Edit") self.editMenu.addAction(self.cutAct) self.editMenu.addAction(self.copyAct) self.editMenu.addAction(self.pasteAct) self.windowMenu = self.menuBar().addMenu("&Window") self.updateWindowMenu() self.windowMenu.aboutToShow.connect(self.updateWindowMenu) self.menuBar().addSeparator() self.helpMenu = self.menuBar().addMenu("&Help") self.helpMenu.addAction(self.aboutAct) self.helpMenu.addAction(self.aboutQtAct) def createToolBars(self): self.fileToolBar = self.addToolBar("File") self.fileToolBar.addAction(self.newAct) self.fileToolBar.addAction(self.openAct) self.fileToolBar.addAction(self.saveAct) self.editToolBar = self.addToolBar("Edit") self.editToolBar.addAction(self.cutAct) self.editToolBar.addAction(self.copyAct) self.editToolBar.addAction(self.pasteAct) def createStatusBar(self): self.statusBar().showMessage("Ready") def readSettings(self): settings = QSettings('Trolltech', 'MDI Example') pos = settings.value('pos', QPoint(200, 200)) size = settings.value('size', QSize(400, 400)) self.move(pos) self.resize(size) def writeSettings(self): settings = QSettings('Trolltech', 'MDI Example') settings.setValue('pos', self.pos()) settings.setValue('size', self.size()) def activeMdiChild(self): activeSubWindow = self.mdiArea.activeSubWindow() if activeSubWindow: return activeSubWindow.widget() return None def findMdiChild(self, fileName): canonicalFilePath = QFileInfo(fileName).canonicalFilePath() for window in self.mdiArea.subWindowList(): if window.widget().currentFile() == canonicalFilePath: return window return None def switchLayoutDirection(self): if self.layoutDirection() == Qt.LeftToRight: QApplication.setLayoutDirection(Qt.RightToLeft) else: QApplication.setLayoutDirection(Qt.LeftToRight) def setActiveSubWindow(self, window): if window: self.mdiArea.setActiveSubWindow(window) def contextMenuEvent(self, event): menu = QMenu(self) menu.addAction(self.cutAct) menu.addAction(self.copyAct) menu.addAction(self.pasteAct) menu.addAction(self.suggestAct) menu.exec_(event.globalPos())
class MainWindow(QMainWindow): """This create the main window of the application""" def __init__(self): super(MainWindow, self).__init__() self.ports = serial.listports() self.port = None # remove close & maximize window buttons #self.setWindowFlags(Qt.CustomizeWindowHint|Qt.WindowMinimizeButtonHint) self.setMinimumSize(850, 450) self.mdiArea = QMdiArea() self.mdiArea.setHorizontalScrollBarPolicy(Qt.ScrollBarAsNeeded) self.mdiArea.setVerticalScrollBarPolicy(Qt.ScrollBarAsNeeded) self.setCentralWidget(self.mdiArea) self.mdiArea.subWindowActivated.connect(self.updateMenus) self.mdiArea.setViewMode(QMdiArea.TabbedView) self.windowMapper = QSignalMapper(self) self.windowMapper.mapped[QWidget].connect(self.setActiveSubWindow) self.child = None self.createActions() self.createMenus() self.createStatusBar() self.updateMenus() self.readSettings() self.setWindowTitle("VISCAM") mytoolbar = QToolBar() ports_menu = QComboBox() ports_menu.addItem('Output Port') ports_menu.insertSeparator(1) for port in self.ports: ports_menu.addItem(port) self.ports_menu = ports_menu ports_menu.currentTextChanged.connect(self.setActivePort) mytoolbar.addWidget(ports_menu) mytoolbar.addSeparator() mytoolbar.setMovable(False) mytoolbar.setFixedHeight(60) self.addToolBar(Qt.TopToolBarArea, mytoolbar) def closeEvent(self, scenario): self.mdiArea.closeAllSubWindows() if self.mdiArea.currentSubWindow(): scenario.ignore() else: self.writeSettings() scenario.accept() def about(self): QMessageBox.about( self, "About Viscam", "<b>Viscam</b> controls and manage your video camera through VISCA protocol." "This release is an alpha version. Don't use it in production !!") def updateMenus(self): hasCamera = (self.activeCamera() is not None) self.nextAct.setEnabled(hasCamera) self.previousAct.setEnabled(hasCamera) self.separatorAct.setVisible(hasCamera) def updatePortMenu(self): self.PortMenu.clear() for i, port in enumerate(self.ports): text = "%d %s" % (i + 1, port) if i < 9: text = '&' + text action = self.PortMenu.addAction(text) action.setCheckable(True) if port == self.port: action.setChecked(True) action.triggered.connect(self.setActivePort) def updateWindowMenu(self): self.windowMenu.clear() self.windowMenu.addAction(self.nextAct) self.windowMenu.addAction(self.previousAct) self.windowMenu.addAction(self.separatorAct) windows = self.mdiArea.subWindowList() self.separatorAct.setVisible(len(windows) != 0) for i, window in enumerate(windows): child = window.widget() text = "%d %s" % (i + 1, child.userFriendlyCurrentFile()) if i < 9: text = '&' + text action = self.windowMenu.addAction(text) action.setCheckable(True) action.setChecked(child is self.activeCamera()) action.triggered.connect(self.windowMapper.map) self.windowMapper.setMapping(action, window) def createCamera(self): child = Camera(serial) self.mdiArea.addSubWindow(child) child.newFile() self.child = child return child def createActions(self): self.exitAct = QAction( "E&xit", self, shortcut=QKeySequence.Quit, statusTip="Exit the application", triggered=QApplication.instance().closeAllWindows) self.closeAct = QAction("Cl&ose", self, statusTip="Close the active window", triggered=self.mdiArea.closeActiveSubWindow) self.closeAllAct = QAction("Close &All", self, statusTip="Close all the windows", triggered=self.mdiArea.closeAllSubWindows) self.nextAct = QAction("Ne&xt", self, shortcut=QKeySequence.NextChild, statusTip="Move the focus to the next window", triggered=self.mdiArea.activateNextSubWindow) self.previousAct = QAction( "Pre&vious", self, shortcut=QKeySequence.PreviousChild, statusTip="Move the focus to the previous window", triggered=self.mdiArea.activatePreviousSubWindow) self.separatorAct = QAction(self) self.separatorAct.setSeparator(True) self.aboutAct = QAction("&About", self, statusTip="Show the application's About box", triggered=self.about) def createMenus(self): self.fileMenu = self.menuBar().addMenu("&File") self.fileMenu.addAction(self.exitAct) self.PortMenu = self.menuBar().addMenu("&Ports") self.updatePortMenu() self.PortMenu.aboutToShow.connect(self.updatePortMenu) self.windowMenu = self.menuBar().addMenu("&Window") self.updateWindowMenu() self.windowMenu.aboutToShow.connect(self.updateWindowMenu) self.menuBar().addSeparator() self.helpMenu = self.menuBar().addMenu("&Help") self.helpMenu.addAction(self.aboutAct) def createStatusBar(self): self.statusBar().showMessage("Ready") def readSettings(self): settings = QSettings('Pixel Stereo', 'viscam') port = settings.value('port') pos = settings.value('pos', QPoint(200, 200)) size = settings.value('size', QSize(1000, 650)) self.move(pos) self.resize(size) def writeSettings(self): settings = QSettings('Pixel Stereo', 'viscam') settings.setValue('port', self.port) settings.setValue('pos', self.pos()) settings.setValue('size', self.size()) def activeCamera(self): activeSubWindow = self.mdiArea.activeSubWindow() if activeSubWindow: return activeSubWindow.widget() else: return None def findCamera(self, fileName): canonicalFilePath = QFileInfo(fileName).canonicalFilePath() for window in self.mdiArea.subWindowList(): if window.widget().currentFile() == canonicalFilePath: return window return None def setActiveSubWindow(self, window): if window: self.mdiArea.setActiveSubWindow(window) def setActivePort(self): self.port = self.ports_menu.currentText().encode('utf-8') self.updatePortMenu() serial.open(portname=self.port) viscams = _cmd_adress_set(serial) _if_clear(serial) for v in viscams: v = self.createCamera()
class CalculatorWindow(NodeEditorWindow): """Class representing the MainWindow of the application. Instance Attributes: name_company and name_product - used to register the settings """ def initUI(self): """UI is composed with """ # variable for QSettings self.name_company = 'Michelin' self.name_product = 'Calculator NodeEditor' # Load filesheets self.stylesheet_filename = os.path.join(os.path.dirname(__file__), 'qss/nodeeditor.qss') loadStylessheets( os.path.join(os.path.dirname(__file__), 'qss/nodeeditor-dark.qss'), self.stylesheet_filename) self.empty_icon = QIcon(".") if DEBUG: print('Registered Node') pp(CALC_NODES) # Instantiate the MultiDocument Area self.mdiArea = QMdiArea() self.mdiArea.setHorizontalScrollBarPolicy(Qt.ScrollBarAsNeeded) self.mdiArea.setVerticalScrollBarPolicy(Qt.ScrollBarAsNeeded) self.mdiArea.setViewMode(QMdiArea.TabbedView) self.mdiArea.setTabsClosable(True) self.setCentralWidget(self.mdiArea) # Connect subWindowActivate to updateMenu # Activate the items on the file_menu and the edit_menu self.mdiArea.subWindowActivated.connect(self.updateMenus) # from mdi example... self.windowMapper = QSignalMapper(self) self.windowMapper.mapped[QWidget].connect(self.setActiveSubWindow) # instantiate various elements self.createNodesDock() self.createActions() self.createMenus() self.createToolBars() self.createStatusBar() self.updateMenus() self.readSettings() self.setWindowTitle("Calculator NodeEditor Example") def createActions(self): """Instantiate various `QAction` for the main toolbar. File and Edit menu actions are instantiated in the :classs:~`node_editor.node_editor_widget.NodeEditorWidget` Window and Help actions are specific to the :class:~`examples.calc_window.CalcWindow` """ super().createActions() self.actClose = QAction("Cl&ose", self, statusTip="Close the active window", triggered=self.mdiArea.closeActiveSubWindow) self.actCloseAll = QAction("Close &All", self, statusTip="Close all the windows", triggered=self.mdiArea.closeAllSubWindows) self.actTile = QAction("&Tile", self, statusTip="Tile the windows", triggered=self.mdiArea.tileSubWindows) self.actCascade = QAction("&Cascade", self, statusTip="Cascade the windows", triggered=self.mdiArea.cascadeSubWindows) self.actNext = QAction("Ne&xt", self, shortcut=QKeySequence.NextChild, statusTip="Move the focus to the next window", triggered=self.mdiArea.activateNextSubWindow) self.actPrevious = QAction( "Pre&vious", self, shortcut=QKeySequence.PreviousChild, statusTip="Move the focus to the previous window", triggered=self.mdiArea.activatePreviousSubWindow) self.actSeparator = QAction(self) self.actSeparator.setSeparator(True) self.actAbout = QAction("&About", self, statusTip="Show the application's About box", triggered=self.about) def createMenus(self): """Populate File, Edit, Window and Help with `QAction`""" super().createMenus() self.windowMenu = self.menuBar().addMenu("&Window") self.updateWindowMenu() self.windowMenu.aboutToShow.connect(self.updateWindowMenu) self.menuBar().addSeparator() self.helpMenu = self.menuBar().addMenu("&Help") self.helpMenu.addAction(self.actAbout) # Any time the edit menu is about to be shown, update it self.editMenu.aboutToShow.connect(self.updateEditMenu) def onWindowNodesToolbar(self): """Event handling the visibility of the `Nodes Dock`""" if self.nodesDock.isVisible(): self.nodesDock.hide() else: self.nodesDock.show() def createToolBars(self): pass def createNodesDock(self): """Create `Nodes Dock` and populates it with the list of `Nodes` The `Nodes` are automatically detected via the :class:~`examples.calc_drag_listbox.QNEDragListBox` """ self.nodeListWidget = QNEDragListbox() self.nodesDock = QDockWidget("Nodes") self.nodesDock.setWidget(self.nodeListWidget) self.nodesDock.setFloating(False) self.addDockWidget(Qt.RightDockWidgetArea, self.nodesDock) def createStatusBar(self): self.statusBar().showMessage("Ready", ) def updateMenus(self): active = self.getCurrentNodeEditorWidget() hasMdiChild = (active is not None) self.actSave.setEnabled(hasMdiChild) self.actSaveAs.setEnabled(hasMdiChild) self.actClose.setEnabled(hasMdiChild) self.actCloseAll.setEnabled(hasMdiChild) self.actTile.setEnabled(hasMdiChild) self.actCascade.setEnabled(hasMdiChild) self.actNext.setEnabled(hasMdiChild) self.actPrevious.setEnabled(hasMdiChild) self.actSeparator.setVisible(hasMdiChild) self.updateEditMenu() def updateEditMenu(self): if DEBUG: print('updateEditMenu') try: active = self.getCurrentNodeEditorWidget() hasMdiChild = (active is not None) hasSelectedItems = hasMdiChild and active.hasSelectedItems() self.actPaste.setEnabled(hasMdiChild) self.actCut.setEnabled(hasSelectedItems) self.actCopy.setEnabled(hasSelectedItems) self.actDelete.setEnabled(hasSelectedItems) self.actUndo.setEnabled(hasMdiChild and active.canUndo()) self.actRedo.setEnabled(hasMdiChild and active.canRedo()) except Exception as e: dumpException(e) def updateWindowMenu(self): self.windowMenu.clear() toolbar_nodes = self.windowMenu.addAction('Nodes toolbar') toolbar_nodes.setCheckable(True) toolbar_nodes.triggered.connect(self.onWindowNodesToolbar) toolbar_nodes.setChecked(self.nodesDock.isVisible()) self.windowMenu.addSeparator() self.windowMenu.addAction(self.actClose) self.windowMenu.addAction(self.actCloseAll) self.windowMenu.addSeparator() self.windowMenu.addAction(self.actTile) self.windowMenu.addAction(self.actCascade) self.windowMenu.addSeparator() self.windowMenu.addAction(self.actNext) self.windowMenu.addAction(self.actPrevious) self.windowMenu.addAction(self.actSeparator) windows = self.mdiArea.subWindowList() self.actSeparator.setVisible(len(windows) != 0) for i, window in enumerate(windows): child = window.widget() text = "%d %s" % (i + 1, child.getUserFriendlyFilename()) if i < 9: text = '&' + text action = self.windowMenu.addAction(text) action.setCheckable(True) action.setChecked(child is self.getCurrentNodeEditorWidget()) action.triggered.connect(self.windowMapper.map) self.windowMapper.setMapping(action, window) def getCurrentNodeEditorWidget(self) -> NodeEditorWidget: """Return the widget currently holding the scene. For different application, the method can be overridden to return mdiArea, the central widget... Returns ------- NodeEditorWidget Node editor Widget. The widget holding the scene. """ activeSubWindow = self.mdiArea.activeSubWindow() if activeSubWindow: return activeSubWindow.widget() return None def onFileNew(self): try: subwnd = self.createMdiChild() subwnd.widget().fileNew() subwnd.show() except Exception as e: dumpException(e) def onFileOpen(self): """Open OpenFileDialog""" # OpenFile dialog fnames, filter = QFileDialog.getOpenFileNames( self, 'Open graph from file', self.getFileDialogDirectory(), self.getFileDialogFilter()) try: for fname in fnames: if fname: existing = self.findMdiChild(fname) if existing: self.mdiArea.setActiveSubWindow(existing) else: # do not use createMdiChild as a new node editor to call the fileLoad method # Create new subwindow and open file nodeeditor = CalculatorSubWindow() if nodeeditor.fileLoad(fname): self.statusBar().showMessage( f'File {fname} loaded', 5000) nodeeditor.setTitle() subwnd = self.createMdiChild(nodeeditor) subwnd.show() else: nodeeditor.close() except Exception as e: dumpException(e) def about(self): QMessageBox.about( self, "About Calculator NodeEditor Example", "The <b>Calculator NodeEditor</b> example demonstrates how to write multiple " "document interface applications using PyQt5 and NodeEditor.") def closeEvent(self, event: QCloseEvent) -> None: try: self.mdiArea.closeAllSubWindows() if self.mdiArea.currentSubWindow(): event.ignore() else: self.writeSettings() event.accept() # In case of fixing the application closing # import sys # sys.exit(0) except Exception as e: dumpException(e) def createMdiChild(self, child_widget=None): nodeeditor = child_widget if child_widget is not None else CalculatorSubWindow( ) subwnd = self.mdiArea.addSubWindow(nodeeditor, ) subwnd.setWindowIcon(self.empty_icon) # nodeeditor.scene.addItemSelectedListener(self.updateEditMenu) # nodeeditor.scene.addItemsDeselectedListener(self.updateEditMenu) nodeeditor.scene.history.addHistoryModifiedListener( self.updateEditMenu) nodeeditor.addCloseEventListener(self.onSubWndClose) return subwnd def onSubWndClose(self, widget: CalculatorSubWindow, event: QCloseEvent): # close event from the nodeeditor works by asking the active widget # if modification occurs on the active widget, ask to save or not. # Therefore when closing a subwindow, select the corresponding subwindow existing = self.findMdiChild(widget.filename) self.mdiArea.setActiveSubWindow(existing) # Does the active widget need to be saved ? if self.maybeSave(): event.accept() else: event.ignore() def findMdiChild(self, fileName): for window in self.mdiArea.subWindowList(): if window.widget().filename == fileName: return window return None def setActiveSubWindow(self, window): if window: self.mdiArea.setActiveSubWindow(window)
class RDFNavigator(QMainWindow): output_message = pyqtSignal(str) def __init__(self): super(RDFNavigator, self).__init__() self.lastDir = '.' self.settingsManager = RDFNavigatorSettignsManager() self.resourceRefManager = RDFNavigatorResourceReferenceManager() self.childrenFactory = RDFNavigatorChildrenFactory(self) self.mdiArea = QMdiArea() self.mdiArea.setHorizontalScrollBarPolicy(Qt.ScrollBarAsNeeded) self.mdiArea.setVerticalScrollBarPolicy(Qt.ScrollBarAsNeeded) self.setCentralWidget(self.mdiArea) self.mdiArea.subWindowActivated.connect(self.updateMenus) self.windowMapper = QSignalMapper(self) self.windowMapper.mapped[QWidget].connect(self.setActiveSubWindow) self.createActions() self.createMenus() self.createToolBars() self.createStatusBar() self.updateMenus() self.createDockWidgets() self.readSettings() self.setWindowTitle("RDF Navigator") self.global_data = {} self.analyzeSystemData() #self.setStyleSheet("""QToolTip { background-color: black; color: white; border: black solid 1px }""") def closeEvent(self, event): self.mdiArea.closeAllSubWindows() if self.mdiArea.currentSubWindow(): event.ignore() else: self.writeSettings() event.accept() def newFile(self, fileType): child = self.createMdiChild(fileType) child.newFile() child.show() def openFileHelper(self, fileName, fileType): if fileName: self.lastDir = os.path.dirname(fileName) existing = self.findMdiChild(fileName) if existing: self.mdiArea.setActiveSubWindow(existing) return child = self.createMdiChild(fileType) child.setManager(self.settingsManager) if child.loadFile(fileName): self.statusBar().showMessage("File loaded", 2000) child.show() else: child.close() def open(self): fileName, _ = QFileDialog.getOpenFileName( self, "Open runntime data format file", self.lastDir, "RDF Files (*.RDF);;XML Files (*.xml)") self.openFileHelper(fileName, RDFNavigatorChildrenTypes.XML) def openProject(self): fileName, _ = QFileDialog.getOpenFileName( self, "Open XML schema project file", self.lastDir, "XML Schema Files (*.xsd);;") self.openFileHelper(fileName, RDFNavigatorChildrenTypes.SCHEMA) child = self.findMdiChild(fileName) if child: schema = RDFNavigatorXmlSchema() schema.validation_message.connect(self.output_message) schema.setSchemaPath(fileName) graph = schema.getSchemaDependencyGraph() self.projectStructureWidget.createProjectTree( fileName, graph, RDFNavigatorChildrenTypes.SCHEMA) self.projectStructureWidget.open_file_request.connect( self.openFileHelper) def openTemplate(self): fileName, _ = QFileDialog.getOpenFileName( self, "Open system data template file", self.lastDir, "XML Template Files (*.xml);;") self.openFileHelper(fileName, RDFNavigatorChildrenTypes.TEMPLATE) child = self.findMdiChild(fileName) if child: schema = RDFNavigatorXmlSchema() schema.validation_message.connect(self.output_message) schema.setSchemaPath(fileName) graph = schema.getTemplateDependencyGraph() self.projectStructureWidget.createProjectTree( fileName, graph, RDFNavigatorChildrenTypes.TEMPLATE) self.projectStructureWidget.createObjectsTree(fileName) self.projectStructureWidget.createFileSystemTree(fileName) self.projectStructureWidget.open_file_request.connect( self.openFileHelper) self.analyzeTemplateData(os.path.dirname(fileName)) def save(self): if self.activeMdiChild() and self.activeMdiChild().save(): self.statusBar().showMessage("File saved", 2000) def saveAs(self): if self.activeMdiChild() and self.activeMdiChild().saveAs(): self.statusBar().showMessage("File saved", 2000) def cut(self): if self.activeMdiChild(): self.activeMdiChild().cut() def copy(self): if self.activeMdiChild(): self.activeMdiChild().copy() def paste(self): if self.activeMdiChild(): self.activeMdiChild().paste() def activateFind(self): child = self.activeMdiChild() find = RDFNavigatorFind(self) find.findAllCurrentClicked.connect(child.findAll) find.findNextClicked.connect(child.findNextWord) find.findCountClicked.connect(child.countWord) if child.hasSelectedText(): text = child.selectedText() find.setFindText(text) find.show() def about(self): QMessageBox.about(self, "About RDF Navigator", "Tool to simplify work with RDF data") def updateMenus(self): hasMdiChild = (self.activeMdiChild() is not None) self.saveAct.setEnabled(hasMdiChild) self.saveAsAct.setEnabled(hasMdiChild) self.pasteAct.setEnabled(hasMdiChild) self.closeAct.setEnabled(hasMdiChild) self.closeAllAct.setEnabled(hasMdiChild) self.tileAct.setEnabled(hasMdiChild) self.cascadeAct.setEnabled(hasMdiChild) self.nextAct.setEnabled(hasMdiChild) self.previousAct.setEnabled(hasMdiChild) self.separatorAct.setVisible(hasMdiChild) hasSelection = (self.activeMdiChild() is not None and self.activeMdiChild().hasSelectedText()) self.cutAct.setEnabled(hasSelection) self.copyAct.setEnabled(hasSelection) def updateWindowMenu(self): self.windowMenu.clear() self.windowMenu.addAction(self.closeAct) self.windowMenu.addAction(self.closeAllAct) self.windowMenu.addSeparator() self.windowMenu.addAction(self.tileAct) self.windowMenu.addAction(self.cascadeAct) self.windowMenu.addSeparator() self.windowMenu.addAction(self.nextAct) self.windowMenu.addAction(self.previousAct) self.windowMenu.addAction(self.separatorAct) windows = self.mdiArea.subWindowList() self.separatorAct.setVisible(len(windows) != 0) for i, window in enumerate(windows): child = window.widget() text = "%d %s" % (i + 1, child.userFriendlyCurrentFile()) if i < 9: text = '&' + text action = self.windowMenu.addAction(text) action.setCheckable(True) action.setChecked(child is self.activeMdiChild()) action.triggered.connect(self.windowMapper.map) self.windowMapper.setMapping(action, window) def createMdiChild(self, childType): child = self.childrenFactory.createObject(childType) self.mdiArea.addSubWindow(child) child.copyAvailable.connect(self.cutAct.setEnabled) child.copyAvailable.connect(self.copyAct.setEnabled) return child def createActions(self): self.newAct = QAction(QIcon(':/images/new.png'), "&New", self, shortcut=QKeySequence.New, statusTip="Create a new file", triggered=self.newFile) self.openFileAct = QAction(QIcon(':/images/open.png'), "&Open file...", self, shortcut=QKeySequence.Open, statusTip="Open an existing file", triggered=self.open) self.openProjectAct = QAction(QIcon(':/images/openProject.png'), "&Open project...", self, shortcut=QKeySequence("Ctrl+Shift+O"), statusTip="Open an existing project", triggered=self.openProject) self.openTemplate = QAction(QIcon(':/images/sdt.png'), "&Open template...", self, shortcut=QKeySequence("Alt+Shift+O"), statusTip="Open an existing template", triggered=self.openTemplate) self.saveAct = QAction(QIcon(':/images/save.png'), "&Save", self, shortcut=QKeySequence.Save, statusTip="Save the document to disk", triggered=self.save) self.saveAsAct = QAction( "Save &As...", self, shortcut=QKeySequence.SaveAs, statusTip="Save the document under a new name", triggered=self.saveAs) self.exitAct = QAction( "E&xit", self, shortcut=QKeySequence.Quit, statusTip="Exit the application", triggered=QApplication.instance().closeAllWindows) self.cutAct = QAction( QIcon(':/images/cut.png'), "Cu&t", self, shortcut=QKeySequence.Cut, statusTip="Cut the current selection's contents to the clipboard", triggered=self.cut) self.copyAct = QAction( QIcon(':/images/copy.png'), "&Copy", self, shortcut=QKeySequence.Copy, statusTip="Copy the current selection's contents to the clipboard", triggered=self.copy) self.pasteAct = QAction( QIcon(':/images/paste.png'), "&Paste", self, shortcut=QKeySequence.Paste, statusTip= "Paste the clipboard's contents into the current selection", triggered=self.paste) self.findAct = QAction(QIcon(':/images/find.png'), "&Find", self, shortcut=QKeySequence.Find, statusTip="Find text", triggered=self.activateFind) self.settingsAct = QAction(QIcon(':/images/settings.png'), "Open settings", self, shortcut=QKeySequence("Ctrl+1"), statusTip="Open Settings", triggered=self.activateSettings) self.showProjectStructAct = QAction( QIcon(':/images/project_structure.png'), "Show structure", self, shortcut=QKeySequence("Alt+1"), statusTip="Show project structure", triggered=self.showProjectStructure) self.showOutputAct = QAction(QIcon(':/images/project_output.png'), "Show output", self, shortcut=QKeySequence("Alt+2"), statusTip="Show output", triggered=self.showOutput) self.showBookmarks = QAction(QIcon(':/images/project_bookmarks.png'), "Show bookmarks", self, shortcut=QKeySequence("Alt+3"), statusTip="Show bookmarks", triggered=self.showBookmarks) self.showAsDiagram = QAction(QIcon(':/images/diagram.png'), "Show as diagram", self, shortcut=QKeySequence("Alt+4"), statusTip="Show document as diagram", triggered=self.showAsDiagram) self.closeAct = QAction("Cl&ose", self, statusTip="Close the active window", triggered=self.mdiArea.closeActiveSubWindow) self.closeAllAct = QAction("Close &All", self, statusTip="Close all the windows", triggered=self.mdiArea.closeAllSubWindows) self.tileAct = QAction("&Tile", self, statusTip="Tile the windows", triggered=self.mdiArea.tileSubWindows) self.cascadeAct = QAction("&Cascade", self, statusTip="Cascade the windows", triggered=self.mdiArea.cascadeSubWindows) self.nextAct = QAction("Ne&xt", self, shortcut=QKeySequence.NextChild, statusTip="Move the focus to the next window", triggered=self.mdiArea.activateNextSubWindow) self.previousAct = QAction( "Pre&vious", self, shortcut=QKeySequence.PreviousChild, statusTip="Move the focus to the previous window", triggered=self.mdiArea.activatePreviousSubWindow) self.separatorAct = QAction(self) self.separatorAct.setSeparator(True) self.aboutAct = QAction("&About", self, statusTip="Show the application's About box", triggered=self.about) self.aboutQtAct = QAction("About &Qt", self, statusTip="Show the Qt library's About box", triggered=QApplication.instance().aboutQt) def createMenus(self): self.fileMenu = self.menuBar().addMenu("&File") self.fileMenu.addAction(self.newAct) self.fileMenu.addAction(self.openFileAct) self.fileMenu.addAction(self.openProjectAct) self.fileMenu.addAction(self.openTemplate) self.fileMenu.addAction(self.saveAct) self.fileMenu.addAction(self.saveAsAct) self.fileMenu.addSeparator() action = self.fileMenu.addAction("Switch layout direction") action.triggered.connect(self.switchLayoutDirection) self.fileMenu.addAction(self.exitAct) self.editMenu = self.menuBar().addMenu("&Edit") self.editMenu.addAction(self.cutAct) self.editMenu.addAction(self.copyAct) self.editMenu.addAction(self.pasteAct) self.editMenu.addAction(self.findAct) self.settingsMenu = self.menuBar().addMenu("Set&tings") self.settingsMenu.addAction(self.settingsAct) self.viewMenu = self.menuBar().addMenu("&View") self.createViewMenu() self.windowMenu = self.menuBar().addMenu("&Window") self.updateWindowMenu() self.windowMenu.aboutToShow.connect(self.updateWindowMenu) self.menuBar().addSeparator() self.helpMenu = self.menuBar().addMenu("&Help") self.helpMenu.addAction(self.aboutAct) self.helpMenu.addAction(self.aboutQtAct) def createToolBars(self): self.fileToolBar = self.addToolBar("File") self.fileToolBar.addAction(self.newAct) self.fileToolBar.addAction(self.openFileAct) self.fileToolBar.addAction(self.openProjectAct) self.fileToolBar.addAction(self.openTemplate) self.fileToolBar.addAction(self.saveAct) self.editToolBar = self.addToolBar("Edit") self.editToolBar.addAction(self.cutAct) self.editToolBar.addAction(self.copyAct) self.editToolBar.addAction(self.pasteAct) def createStatusBar(self): self.statusBar().showMessage("Ready") def createDockWidgets(self): self.projectStructureWidget = RDFNavigatorProjectStructure(self) self.projectStructureDockWidget = QDockWidget("Project structure", self) self.projectStructureDockWidget.setWidget(self.projectStructureWidget) self.addDockWidget(Qt.LeftDockWidgetArea, self.projectStructureDockWidget) self.projectOutputWidget = RDFNavigatorOutput(self) self.projectOutputDockWidget = QDockWidget("Project output", self) self.projectOutputDockWidget.setWidget(self.projectOutputWidget) self.addDockWidget(Qt.BottomDockWidgetArea, self.projectOutputDockWidget) self.output_message.connect(self.projectOutputWidget.write) self.bookmarskWidget = RDFNavigatorBookmarks(self) self.bookmarksDockWidget = QDockWidget("Bookmarks", self) self.bookmarksDockWidget.setWidget(self.bookmarskWidget) self.addDockWidget(Qt.BottomDockWidgetArea, self.bookmarksDockWidget) self.bookmarskWidget.bookmark_ref_requested.connect(self.showBookmark) def readSettings(self): pos = self.settingsManager.getConfig('pos', QPoint(200, 200)) size = self.settingsManager.getConfig('size', QSize(400, 400)) self.lastDir = self.settingsManager.getConfig('lastDir', '') self.move(pos) self.resize(size) def writeSettings(self): self.settingsManager.setConfig('pos', self.pos()) self.settingsManager.setConfig('size', self.size()) self.settingsManager.setConfig('lastDir', self.lastDir) def activeMdiChild(self): activeSubWindow = self.mdiArea.activeSubWindow() if activeSubWindow: return activeSubWindow.widget() return None def findMdiChild(self, fileName): canonicalFilePath = QFileInfo(fileName).canonicalFilePath() for window in self.mdiArea.subWindowList(): if window.widget().currentFile() == canonicalFilePath: return window return None def switchLayoutDirection(self): if self.layoutDirection() == Qt.LeftToRight: QApplication.setLayoutDirection(Qt.RightToLeft) else: QApplication.setLayoutDirection(Qt.LeftToRight) def setActiveSubWindow(self, window): if window: self.mdiArea.setActiveSubWindow(window) def activateSettings(self): settingsDlg = RDFNavigatorSettings(self) settingsDlg.setPluginsPath(self.settingsManager) settingsDlg.setRDFToolsPath(self.settingsManager) settingsDlg.setSchemaPath(self.settingsManager) settingsDlg.setSysDataPath(self.settingsManager) settingsDlg.exec_() settingsDict = settingsDlg.getConfig() map(lambda (x, y): self.settingsManager.setConfig(x, y), settingsDict.items()) def analyzeSystemData(self): self.resourceRefManager.setSysDataPath( self.settingsManager.getConfig('sys_data', '')) self.global_refs_data, self.global_vals_data = self.resourceRefManager.analyzeRefs( ) if self.global_refs_data != {} and self.global_vals_data != {}: self.global_file_refs_data = dict( reduce(lambda x, y: x + y, [[(v, keys) for v in vals] for keys, vals in self.global_refs_data.iteritems() if vals != {}])) def analyzeTemplateData(self, template_path): sysDataPath = self.resourceRefManager.getSysDataPath() self.resourceRefManager.setSysDataPath(template_path) self.template_refs_data, self.template_vals_data = self.resourceRefManager.analyzeRefs( ) if self.template_refs_data != {} and self.template_vals_data != {}: self.template_file_refs_data = dict( reduce(lambda x, y: x + y, [[(v, keys) for v in vals] for keys, vals in self.template_refs_data.iteritems() if vals != {}])) self.resourceRefManager.setSysDataPath(sysDataPath) def showReference(self, obj_name, key_id): child_name = self.template_file_refs_data.get(obj_name) if child_name is None: child_name = self.global_file_refs_data[obj_name] child = self.findMdiChild(child_name) if child is None: self.openFileHelper(child_name, RDFNavigatorChildrenTypes.TEMPLATE) child = self.findMdiChild(child_name) self.mdiArea.setActiveSubWindow(child) line = None try: line = self.template_refs_data[child_name][obj_name][key_id] except KeyError: line = self.global_refs_data[child_name][obj_name][key_id] child.widget().goToLine(line) def showReferenceValue(self, obj_name, key_id): child_name = self.template_file_refs_data.get(obj_name) if child_name is None: child_name = self.global_file_refs_data[obj_name] value = None try: value = self.template_vals_data[child_name][obj_name][key_id] except KeyError: value = self.global_refs_data[child_name][obj_name][key_id] child = self.activeMdiChild() if child is not None: child.displayRefValue(value) def showBookmark(self, filename, line): child = self.findMdiChild(filename) if child is None: self.openFileHelper(filename, RDFNavigatorChildrenTypes.TEMPLATE) child = self.findMdiChild(filename) self.mdiArea.setActiveSubWindow(child) child.widget().goToLine(line) def createViewMenu(self): self.viewMenu.addAction(self.showProjectStructAct) self.viewMenu.addAction(self.showOutputAct) self.viewMenu.addAction(self.showBookmarks) self.viewMenu.addAction(self.showAsDiagram) def showProjectStructure(self): self.projectStructureDockWidget.show() def showOutput(self): self.projectOutputDockWidget.show() def showBookmarks(self): self.bookmarksDockWidget.show() def showAsDiagram(self): from rdfdiagram.rdfdiagramwidget import RdfDiagramWidget rdfdiagram = RdfDiagramWidget(self) self.mdiArea.addSubWindow(rdfdiagram) rdfdiagram.show()
class MDIWindow(QMainWindow): count = 0 def __init__(self): super().__init__() self.data_dict = {} self.mdi = QMdiArea() self.setCentralWidget(self.mdi) # self.mdi.resize(950,950) bar = self.menuBar() self.current_dir = None self.opened_wd_names = [] file = bar.addMenu("File") file.addAction("New") file.addAction("cascade") file.addAction("Tiled") file.triggered[QAction].connect(self.WindowTrig) load = bar.addMenu("Load") load.addAction("2D") load.addAction("3D") load.triggered[QAction].connect(self.dir_open) toolbar = QToolBar() self.addToolBar(toolbar) bw_button_action = QAction('base_wnd', self) bw_button_action.setStatusTip('base window button') bw_button_action.triggered.connect(self.onclicktb) toolbar.addAction(bw_button_action) self.setWindowTitle("MDI Application") self.base_wd = QMdiSubWindow() self.base_wd.setAttribute(Qt.WA_DeleteOnClose, False) self.base_wd.resize(400, 400) self.base_wd.plt_i = pg.PlotItem(labels={ 'left': ('slits', 'degrees'), 'bottom': ('Kin. Energy', 'eV') }) self.base_wd.plt_iv = pg.ImageView(view=self.base_wd.plt_i) self.base_wd.setWidget(self.base_wd.plt_iv) self.base_wd.setWindowTitle("plot window") self.mdi.addSubWindow(self.base_wd) self.base_wd.show() data_DockWidget = QDockWidget('data', self) data_DockWidget.setObjectName(('data window')) data_DockWidget.setAllowedAreas(Qt.RightDockWidgetArea) self.data_list = QListWidget() data_DockWidget.setWidget(self.data_list) self.addDockWidget(Qt.RightDockWidgetArea, data_DockWidget) self.data_list.itemClicked.connect(self.show_data) self.data_list.itemDoubleClicked.connect(self.get_data) self.mdi.subWindowActivated.connect(self.get_data) def WindowTrig(self, p): if p.text() == "New": MDIWindow.count = MDIWindow.count + 1 sub = QMdiSubWindow() sub.setWidget(QTextEdit()) sub.setWindowTitle("Sub Window" + str(MDIWindow.count)) self.mdi.addSubWindow(sub) sub.show() if p.text() == "cascade": self.mdi.cascadeSubWindows() if p.text() == "Tiled": self.mdi.tileSubWindows() def dir_open(self, p): self.current_dir = dlg.File_dlg.openDirNameDialog(self) print(self.current_dir) if p.text() == "2D": print('2D') files_ls = glob.glob(self.current_dir + '/*.ibw') fls = [f[len(self.current_dir) + 1:] for f in files_ls] print(files_ls) self.data_list.addItems(fls) if p.text() == "3D": zip_ls = glob.glob(self.current_dir + '/*.zip') zp = [f[len(self.current_dir) + 1:] for f in zip_ls] print(zp) self.data_list.addItems(zp) def show_data(self, s): print('show data') file_name = s.text() self.data_dict = ut.ibw2dict(self.current_dir + '/' + file_name) e_sc = self.data_dict['E_axis'][1] - self.data_dict['E_axis'][0] a_sc = self.data_dict['A_axis'][1] - self.data_dict['A_axis'][0] e_str = self.data_dict['E_axis'][0] a_str = self.data_dict['A_axis'][0] self.base_wd.plt_i.setRange(xRange=[self.data_dict['E_axis'][0], self.data_dict['E_axis'][-1]], \ yRange=[self.data_dict['A_axis'][0], self.data_dict['A_axis'][-1]], update=True, padding = 0) self.base_wd.plt_i.getViewBox().setLimits(xMin= e_str, xMax = self.data_dict['E_axis'][-1],\ yMin=self.data_dict['A_axis'][0], yMax=self.data_dict['A_axis'][-1]) self.base_wd.plt_iv.setImage( self.data_dict['data'], pos=[self.data_dict['E_axis'][0], self.data_dict['A_axis'][0]], scale=[e_sc, a_sc]) # self.base_wd.plt_iv.ui.histogram.hide() self.base_wd.plt_iv.ui.roiBtn.hide() self.base_wd.plt_iv.ui.menuBtn.hide() def get_data(self, s): if isinstance(s, QMdiSubWindow) and str( s.objectName()) in self.opened_wd_names: sub = self.mdi.currentSubWindow() self.data_dict = ut.ibw2dict(self.current_dir + '/' + str(s.objectName())) elif isinstance(s, QListWidgetItem): file_name = s.text() self.opened_wd_names.append(file_name) MDIWindow.count = MDIWindow.count + 1 sub = QMdiSubWindow() sub.resize(550, 550) sub.setWindowTitle(file_name) sub.setObjectName(file_name) self.data_dict = ut.ibw2dict(self.current_dir + '/' + file_name) else: print(isinstance(s, QMdiSubWindow), isinstance(s, QListWidgetItem)) print(type(s)) return e_sc = self.data_dict['E_axis'][1] - self.data_dict['E_axis'][0] a_sc = self.data_dict['A_axis'][1] - self.data_dict['A_axis'][0] e_rg = self.data_dict['E_axis'][-1] - self.data_dict['E_axis'][0] a_rg = self.data_dict['A_axis'][-1] - self.data_dict['A_axis'][0] e_str = self.data_dict['E_axis'][0] a_str = self.data_dict['A_axis'][0] e_end = self.data_dict['E_axis'][-1] a_end = self.data_dict['A_axis'][-1] print(e_str, a_str) print(e_end, a_end) print(e_rg, a_rg) print(e_sc, a_sc) gr_v = pg.GraphicsView() l = pg.GraphicsLayout() gr_v.setCentralWidget(l) sub.setWidget(gr_v) self.mdi.addSubWindow(sub) sub.show() p1 = l.addPlot(x=[1, 2], y=[1, 2], name="Plot1", title="EDC", pen="r", row=0, col=0) # label1 = pg.LabelItem(justify='right') # p1.addItem(label1) plt_i = pg.PlotItem(labels={ 'left': ('slits', 'degrees'), 'bottom': ('Kin. Energy', 'eV') }) plt_i.setRange(xRange=[e_str, e_end], yRange=[a_str, a_end], update=True, padding=0) vb = plt_i.getViewBox() vb.setLimits(xMin=e_str, xMax=e_end, yMin=a_str, yMax=a_end) vb.setMouseMode(vb.RectMode) l.addItem(plt_i, row=1, col=0) img_i = pg.ImageItem(self.data_dict['data'], border=None) qrect = vb.viewRect() img_i.setRect(qrect) vb.addItem(img_i) vb.autoRange() # vb.invertX() vb.invertY() hist = pg.HistogramLUTItem(image=img_i) l.addItem(hist, row=0, col=1) p2 = l.addPlot(x=[1, 2], y=[2, 1], name="Plot2", title="MDC", pen="g", row=1, col=1) # label2 = pg.LabelItem(justify='left') # plt_i.addItem(label2) # cross hair vLine = pg.InfiniteLine(angle=90, movable=False) hLine = pg.InfiniteLine(angle=0, movable=False) p1.addItem(vLine, ignoreBounds=False) p1.addItem(hLine, ignoreBounds=False) vb1 = p1.vb pcv = plt_i.addLine(x=e_end, pen='r') pch = plt_i.addLine(y=a_str, pen='r') # lROI = pg.ROI(((e_str+e_end)/2,a_str), size=(5*e_sc,a_rg)) # vb.addItem(lROI) # slice, coor = lROI.getArrayRegion(self.data_dict['data'], img_i ,returnMappedCoords = True) # print('slice') # sl_sum=np.sum(slice, axis=0) # print(sl_sum[0:10]) # print(type(slice), slice.shape) # print(type(coor), coor.shape) # print(coor[1,0,0:10]) # p2.invertY() # p2.setYLink(plt_i) # p2.plot(y=coor[1,0,:], x=sl_sum) def onMouseMoved(point): p = vb.mapSceneToView(point) pcv.setValue(p.x()) pch.setValue(p.y()) # print(p.x(), p.y()) hROI = pg.ROI((e_str, p.y()), size=(e_rg, 5 * a_sc)) vb.addItem(hROI) hROI.hide() sl, co = hROI.getArrayRegion(self.data_dict['data'], img_i, returnMappedCoords=True) sl_sum = np.sum(sl, axis=1) p1.setXLink(plt_i) p1.plot(x=co[0, :, 0], y=sl_sum, clear=True) vROI = pg.ROI((p.x(), a_str), size=(5 * e_sc, a_rg)) vb.addItem(vROI) vROI.hide() slc, coo = vROI.getArrayRegion(self.data_dict['data'], img_i, returnMappedCoords=True) sl_sum = np.sum(slc, axis=0) p2.invertY() p2.setYLink(plt_i) p2.plot(y=coo[1, 0, :], x=sl_sum, clear=True) # label2.setText("{}-{}".format(p.x(), p.y())) img_i.scene().sigMouseMoved.connect(onMouseMoved) def onclicktb(self): self.base_wd.plt_i = pg.PlotItem(labels={ 'left': ('slits', 'degrees'), 'bottom': ('Kin. Energy', 'eV') }) self.base_wd.plt_iv = pg.ImageView(view=self.base_wd.plt_i) self.base_wd.setWidget(self.base_wd.plt_iv) self.base_wd.show()
class MainWindow(QMainWindow): def __init__(self): super(MainWindow, self).__init__() self.mdiArea = QMdiArea() self.mdiArea.setHorizontalScrollBarPolicy(Qt.ScrollBarAsNeeded) self.mdiArea.setVerticalScrollBarPolicy(Qt.ScrollBarAsNeeded) self.setCentralWidget(self.mdiArea) self.mdiArea.subWindowActivated.connect(self.updateMenus) self.windowMapper = QSignalMapper(self) self.windowMapper.mapped[QWidget].connect(self.setActiveSubWindow) self.createActions() self.createMenus() self.createStatusBar() self.updateMenus() self.clipboard = QApplication.clipboard() self.setWindowTitle("Qt5 Multi Video Player v0.02 - by Luis Santos AKA DJOKER") def closeEvent(self, event): self.mdiArea.closeAllSubWindows() if self.mdiArea.currentSubWindow(): event.ignore() else: event.accept() def newFile(self): child = VideoPlayer(True) self.mdiArea.addSubWindow(child) url = self.clipboard.text() child.Player(url) child.show() def newMute(self): child = VideoPlayer(False) self.mdiArea.addSubWindow(child) url = self.clipboard.text() child.Player(url) child.show() return def updateMenus(self): hasMdiChild = (self.activeMdiChild() is not None) self.closeAct.setEnabled(hasMdiChild) self.closeAllAct.setEnabled(hasMdiChild) self.tileAct.setEnabled(hasMdiChild) self.cascadeAct.setEnabled(hasMdiChild) self.nextAct.setEnabled(hasMdiChild) self.previousAct.setEnabled(hasMdiChild) self.separatorAct.setVisible(hasMdiChild) def updateWindowMenu(self): self.windowMenu.clear() self.windowMenu.addAction(self.closeAct) self.windowMenu.addAction(self.closeAllAct) self.windowMenu.addSeparator() self.windowMenu.addAction(self.tileAct) self.windowMenu.addAction(self.cascadeAct) self.windowMenu.addSeparator() self.windowMenu.addAction(self.nextAct) self.windowMenu.addAction(self.previousAct) self.windowMenu.addAction(self.separatorAct) windows = self.mdiArea.subWindowList() self.separatorAct.setVisible(len(windows) != 0) def createMdiChild(self): child = MdiChild() self.mdiArea.addSubWindow(child) return child def createActions(self): self.newAct = QAction( "&New", self, shortcut=QKeySequence.New, statusTip="Create a new Video Player", triggered=self.newFile) self.newActCam4 = QAction("&VideoMute", self, shortcut=QKeySequence.New, statusTip="Create a new Video Player Mute", triggered=self.newMute) self.closeAct = QAction("Cl&ose", self, statusTip="Close the active window", triggered=self.mdiArea.closeActiveSubWindow) self.closeAllAct = QAction("Close &All", self, statusTip="Close all the windows", triggered=self.mdiArea.closeAllSubWindows) self.tileAct = QAction("&Tile", self, statusTip="Tile the windows", triggered=self.mdiArea.tileSubWindows) self.cascadeAct = QAction("&Cascade", self, statusTip="Cascade the windows", triggered=self.mdiArea.cascadeSubWindows) self.nextAct = QAction("Ne&xt", self, shortcut=QKeySequence.NextChild, statusTip="Move the focus to the next window", triggered=self.mdiArea.activateNextSubWindow) self.previousAct = QAction("Pre&vious", self, shortcut=QKeySequence.PreviousChild, statusTip="Move the focus to the previous window", triggered=self.mdiArea.activatePreviousSubWindow) self.separatorAct = QAction(self) self.separatorAct.setSeparator(True) def createMenus(self): self.fileMenu = self.menuBar().addMenu("&File") self.fileMenu.addAction(self.newAct) self.fileMenu.addAction(self.newActCam4) self.exitAct = QAction("E&xit", self, shortcut=QKeySequence.Quit, statusTip="Exit the application", triggered=QApplication.instance().closeAllWindows) self.fileMenu.addSeparator() action = self.fileMenu.addAction("Switch layout direction") action.triggered.connect(self.switchLayoutDirection) self.fileMenu.addAction(self.exitAct) self.windowMenu = self.menuBar().addMenu("&Window") self.updateWindowMenu() self.windowMenu.aboutToShow.connect(self.updateWindowMenu) self.menuBar().addSeparator() def createStatusBar(self): self.statusBar().showMessage("Ready") def activeMdiChild(self): activeSubWindow = self.mdiArea.activeSubWindow() if activeSubWindow: return activeSubWindow.widget() return None def findMdiChild(self, fileName): canonicalFilePath = QFileInfo(fileName).canonicalFilePath() for window in self.mdiArea.subWindowList(): if window.widget().currentFile() == canonicalFilePath: return window return None def switchLayoutDirection(self): if self.layoutDirection() == Qt.LeftToRight: QApplication.setLayoutDirection(Qt.RightToLeft) else: QApplication.setLayoutDirection(Qt.LeftToRight) def setActiveSubWindow(self, window): if window: self.mdiArea.setActiveSubWindow(window)
class MainWindow(QMainWindow): def __init__(self): super(MainWindow, self).__init__() self.mdiArea = QMdiArea() self.mdiArea.setHorizontalScrollBarPolicy(Qt.ScrollBarAsNeeded) self.mdiArea.setVerticalScrollBarPolicy(Qt.ScrollBarAsNeeded) self.setCentralWidget(self.mdiArea) self.mdiArea.subWindowActivated.connect(self.updateMenus) self.windowMapper = QSignalMapper(self) self.windowMapper.mapped[QWidget].connect(self.setActiveSubWindow) self.createActions() self.createMenus() self.createToolBars() self.createStatusBar() self.updateMenus() self.readSettings() self.setWindowTitle("MDI") def closeEvent(self, event): self.mdiArea.closeAllSubWindows() if self.mdiArea.currentSubWindow(): event.ignore() else: self.writeSettings() event.accept() def newFile(self): child = self.createMdiChild() child.newFile() child.show() def open(self): fileName, _ = QFileDialog.getOpenFileName(self) if fileName: existing = self.findMdiChild(fileName) if existing: self.mdiArea.setActiveSubWindow(existing) return child = self.createMdiChild() if child.loadFile(fileName): self.statusBar().showMessage("File loaded", 2000) child.show() else: child.close() def save(self): if self.activeMdiChild() and self.activeMdiChild().save(): self.statusBar().showMessage("File saved", 2000) def saveAs(self): if self.activeMdiChild() and self.activeMdiChild().saveAs(): self.statusBar().showMessage("File saved", 2000) def cut(self): if self.activeMdiChild(): self.activeMdiChild().cut() def copy(self): if self.activeMdiChild(): self.activeMdiChild().copy() def paste(self): if self.activeMdiChild(): self.activeMdiChild().paste() def about(self): QMessageBox.about(self, "About MDI", "The <b>MDI</b> example demonstrates how to write multiple " "document interface applications using Qt.") def updateMenus(self): hasMdiChild = (self.activeMdiChild() is not None) self.saveAct.setEnabled(hasMdiChild) self.saveAsAct.setEnabled(hasMdiChild) self.pasteAct.setEnabled(hasMdiChild) self.closeAct.setEnabled(hasMdiChild) self.closeAllAct.setEnabled(hasMdiChild) self.tileAct.setEnabled(hasMdiChild) self.cascadeAct.setEnabled(hasMdiChild) self.nextAct.setEnabled(hasMdiChild) self.previousAct.setEnabled(hasMdiChild) self.separatorAct.setVisible(hasMdiChild) hasSelection = (self.activeMdiChild() is not None and self.activeMdiChild().textCursor().hasSelection()) self.cutAct.setEnabled(hasSelection) self.copyAct.setEnabled(hasSelection) def updateWindowMenu(self): self.windowMenu.clear() self.windowMenu.addAction(self.closeAct) self.windowMenu.addAction(self.closeAllAct) self.windowMenu.addSeparator() self.windowMenu.addAction(self.tileAct) self.windowMenu.addAction(self.cascadeAct) self.windowMenu.addSeparator() self.windowMenu.addAction(self.nextAct) self.windowMenu.addAction(self.previousAct) self.windowMenu.addAction(self.separatorAct) windows = self.mdiArea.subWindowList() self.separatorAct.setVisible(len(windows) != 0) for i, window in enumerate(windows): child = window.widget() text = "%d %s" % (i + 1, child.userFriendlyCurrentFile()) if i < 9: text = '&' + text action = self.windowMenu.addAction(text) action.setCheckable(True) action.setChecked(child is self.activeMdiChild()) action.triggered.connect(self.windowMapper.map) self.windowMapper.setMapping(action, window) def createMdiChild(self): child = MdiChild() self.mdiArea.addSubWindow(child) child.copyAvailable.connect(self.cutAct.setEnabled) child.copyAvailable.connect(self.copyAct.setEnabled) return child def createActions(self): self.newAct = QAction(QIcon(':/images/new.png'), "&New", self, shortcut=QKeySequence.New, statusTip="Create a new file", triggered=self.newFile) self.openAct = QAction(QIcon(':/images/open.png'), "&Open...", self, shortcut=QKeySequence.Open, statusTip="Open an existing file", triggered=self.open) self.saveAct = QAction(QIcon(':/images/save.png'), "&Save", self, shortcut=QKeySequence.Save, statusTip="Save the document to disk", triggered=self.save) self.saveAsAct = QAction("Save &As...", self, shortcut=QKeySequence.SaveAs, statusTip="Save the document under a new name", triggered=self.saveAs) self.exitAct = QAction("E&xit", self, shortcut=QKeySequence.Quit, statusTip="Exit the application", triggered=QApplication.instance().closeAllWindows) self.cutAct = QAction(QIcon(':/images/cut.png'), "Cu&t", self, shortcut=QKeySequence.Cut, statusTip="Cut the current selection's contents to the clipboard", triggered=self.cut) self.copyAct = QAction(QIcon(':/images/copy.png'), "&Copy", self, shortcut=QKeySequence.Copy, statusTip="Copy the current selection's contents to the clipboard", triggered=self.copy) self.pasteAct = QAction(QIcon(':/images/paste.png'), "&Paste", self, shortcut=QKeySequence.Paste, statusTip="Paste the clipboard's contents into the current selection", triggered=self.paste) self.closeAct = QAction("Cl&ose", self, statusTip="Close the active window", triggered=self.mdiArea.closeActiveSubWindow) self.closeAllAct = QAction("Close &All", self, statusTip="Close all the windows", triggered=self.mdiArea.closeAllSubWindows) self.tileAct = QAction("&Tile", self, statusTip="Tile the windows", triggered=self.mdiArea.tileSubWindows) self.cascadeAct = QAction("&Cascade", self, statusTip="Cascade the windows", triggered=self.mdiArea.cascadeSubWindows) self.nextAct = QAction("Ne&xt", self, shortcut=QKeySequence.NextChild, statusTip="Move the focus to the next window", triggered=self.mdiArea.activateNextSubWindow) self.previousAct = QAction("Pre&vious", self, shortcut=QKeySequence.PreviousChild, statusTip="Move the focus to the previous window", triggered=self.mdiArea.activatePreviousSubWindow) self.separatorAct = QAction(self) self.separatorAct.setSeparator(True) self.aboutAct = QAction("&About", self, statusTip="Show the application's About box", triggered=self.about) self.aboutQtAct = QAction("About &Qt", self, statusTip="Show the Qt library's About box", triggered=QApplication.instance().aboutQt) def createMenus(self): self.fileMenu = self.menuBar().addMenu("&File") self.fileMenu.addAction(self.newAct) self.fileMenu.addAction(self.openAct) self.fileMenu.addAction(self.saveAct) self.fileMenu.addAction(self.saveAsAct) self.fileMenu.addSeparator() action = self.fileMenu.addAction("Switch layout direction") action.triggered.connect(self.switchLayoutDirection) self.fileMenu.addAction(self.exitAct) self.editMenu = self.menuBar().addMenu("&Edit") self.editMenu.addAction(self.cutAct) self.editMenu.addAction(self.copyAct) self.editMenu.addAction(self.pasteAct) self.windowMenu = self.menuBar().addMenu("&Window") self.updateWindowMenu() self.windowMenu.aboutToShow.connect(self.updateWindowMenu) self.menuBar().addSeparator() self.helpMenu = self.menuBar().addMenu("&Help") self.helpMenu.addAction(self.aboutAct) self.helpMenu.addAction(self.aboutQtAct) def createToolBars(self): self.fileToolBar = self.addToolBar("File") self.fileToolBar.addAction(self.newAct) self.fileToolBar.addAction(self.openAct) self.fileToolBar.addAction(self.saveAct) self.editToolBar = self.addToolBar("Edit") self.editToolBar.addAction(self.cutAct) self.editToolBar.addAction(self.copyAct) self.editToolBar.addAction(self.pasteAct) def createStatusBar(self): self.statusBar().showMessage("Ready") def readSettings(self): settings = QSettings('Trolltech', 'MDI Example') pos = settings.value('pos', QPoint(200, 200)) size = settings.value('size', QSize(400, 400)) self.move(pos) self.resize(size) def writeSettings(self): settings = QSettings('Trolltech', 'MDI Example') settings.setValue('pos', self.pos()) settings.setValue('size', self.size()) def activeMdiChild(self): activeSubWindow = self.mdiArea.activeSubWindow() if activeSubWindow: return activeSubWindow.widget() return None def findMdiChild(self, fileName): canonicalFilePath = QFileInfo(fileName).canonicalFilePath() for window in self.mdiArea.subWindowList(): if window.widget().currentFile() == canonicalFilePath: return window return None def switchLayoutDirection(self): if self.layoutDirection() == Qt.LeftToRight: QApplication.setLayoutDirection(Qt.RightToLeft) else: QApplication.setLayoutDirection(Qt.LeftToRight) def setActiveSubWindow(self, window): if window: self.mdiArea.setActiveSubWindow(window)
class MainWindow(QMainWindow): def __init__(self): super(MainWindow, self).__init__() self.mdiArea = QMdiArea() self.mdiArea.setHorizontalScrollBarPolicy(Qt.ScrollBarAsNeeded) self.mdiArea.setVerticalScrollBarPolicy(Qt.ScrollBarAsNeeded) self.setCentralWidget(self.mdiArea) self.mdiArea.subWindowActivated.connect(self.updateMenus) self.windowMapper = QSignalMapper(self) self.windowMapper.mapped[QWidget].connect(self.setActiveSubWindow) self.createActions() self.createMenus() self.createStatusBar() self.updateMenus() self.setWindowTitle("MDI") def closeEvent(self, event): self.mdiArea.closeAllSubWindows() if self.mdiArea.currentSubWindow(): event.ignore() else: event.accept() def newFile(self): child = BrowserChaturbate(self.mdiArea) self.mdiArea.addSubWindow(child) child.load("https://www.chaturbate.com/") child.resize(320, 240) child.show() def newCam4(self): child = BrowserCam4(self.mdiArea) self.mdiArea.addSubWindow(child) child.load("https://www.cam4.com") child.resize(320, 240) child.show() def newFreecam(self): child = BrowserMyFreeCams(self.mdiArea) self.mdiArea.addSubWindow(child) #child.load("https://www.myfreecams.com/php/online_models_splash.php?") child.load('https://www.pornhub.com/categories?o=al') child.resize(320, 240) child.show() def updateMenus(self): hasMdiChild = (self.activeMdiChild() is not None) self.closeAct.setEnabled(hasMdiChild) self.closeAllAct.setEnabled(hasMdiChild) self.tileAct.setEnabled(hasMdiChild) self.cascadeAct.setEnabled(hasMdiChild) self.nextAct.setEnabled(hasMdiChild) self.previousAct.setEnabled(hasMdiChild) self.separatorAct.setVisible(hasMdiChild) def updateWindowMenu(self): self.windowMenu.clear() self.windowMenu.addAction(self.closeAct) self.windowMenu.addAction(self.closeAllAct) self.windowMenu.addSeparator() self.windowMenu.addAction(self.tileAct) self.windowMenu.addAction(self.cascadeAct) self.windowMenu.addSeparator() self.windowMenu.addAction(self.nextAct) self.windowMenu.addAction(self.previousAct) self.windowMenu.addAction(self.separatorAct) windows = self.mdiArea.subWindowList() self.separatorAct.setVisible(len(windows) != 0) def createActions(self): self.newAct = QAction("&Chartubate", self, shortcut=QKeySequence.New, statusTip="Browse Chartubate", triggered=self.newFile) self.newActCam4 = QAction("&Cam4", self, shortcut=QKeySequence.New, statusTip="Browse Cam4", triggered=self.newCam4) self.newActFreeCam = QAction("&PornHub", self, shortcut=QKeySequence.New, statusTip="Browse PornHub", triggered=self.newFreecam) self.closeAct = QAction("Cl&ose", self, statusTip="Close the active window", triggered=self.mdiArea.closeActiveSubWindow) self.closeAllAct = QAction("Close &All", self, statusTip="Close all the windows", triggered=self.mdiArea.closeAllSubWindows) self.tileAct = QAction("&Tile", self, statusTip="Tile the windows", triggered=self.mdiArea.tileSubWindows) self.cascadeAct = QAction("&Cascade", self, statusTip="Cascade the windows", triggered=self.mdiArea.cascadeSubWindows) self.nextAct = QAction("Ne&xt", self, shortcut=QKeySequence.NextChild, statusTip="Move the focus to the next window", triggered=self.mdiArea.activateNextSubWindow) self.previousAct = QAction( "Pre&vious", self, shortcut=QKeySequence.PreviousChild, statusTip="Move the focus to the previous window", triggered=self.mdiArea.activatePreviousSubWindow) self.separatorAct = QAction(self) self.separatorAct.setSeparator(True) def createMenus(self): self.fileMenu = self.menuBar().addMenu("&File") self.fileMenu.addAction(self.newAct) self.fileMenu.addAction(self.newActCam4) self.fileMenu.addAction(self.newActFreeCam) self.exitAct = QAction( "E&xit", self, shortcut=QKeySequence.Quit, statusTip="Exit the application", triggered=QApplication.instance().closeAllWindows) self.fileMenu.addSeparator() action = self.fileMenu.addAction("Switch layout direction") action.triggered.connect(self.switchLayoutDirection) self.fileMenu.addAction(self.exitAct) self.windowMenu = self.menuBar().addMenu("&Window") self.updateWindowMenu() self.windowMenu.aboutToShow.connect(self.updateWindowMenu) self.menuBar().addSeparator() def createStatusBar(self): self.statusBar().showMessage("Ready") def activeMdiChild(self): activeSubWindow = self.mdiArea.activeSubWindow() if activeSubWindow: return activeSubWindow.widget() return None def findMdiChild(self, fileName): canonicalFilePath = QFileInfo(fileName).canonicalFilePath() for window in self.mdiArea.subWindowList(): if window.widget().currentFile() == canonicalFilePath: return window return None def switchLayoutDirection(self): if self.layoutDirection() == Qt.LeftToRight: QApplication.setLayoutDirection(Qt.RightToLeft) else: QApplication.setLayoutDirection(Qt.LeftToRight) def setActiveSubWindow(self, window): if window: self.mdiArea.setActiveSubWindow(window)