def on_show_debug_menu(self): self.debug_menu.clear() if self.is_master_cmd or self.power_user: power_user_mode = QAction('Power User Mode', self) power_user_mode.setCheckable(True) power_user_mode.setChecked(MTTSettings.value('powerUser')) power_user_mode.triggered.connect(self.__on_toggle_power_user) self.debug_menu.addAction(power_user_mode) self.is_master_cmd = False self.debug_menu.addSeparator() open_pref_folder_action = QAction('Open Preferences Folder', self) open_pref_folder_action.setStatusTip('Open MTT preference folder') open_pref_folder_action.triggered.connect(self.on_open_preference_folder) self.debug_menu.addAction(open_pref_folder_action) self.debug_menu.addSeparator() database_dump_csv = QAction('Dump Database as CSV', self) database_dump_csv.triggered.connect(self.view.model.database_dump_csv) self.debug_menu.addAction(database_dump_csv) database_dump_sql = QAction('Dump Database as SQL', self) database_dump_sql.triggered.connect(self.view.model.database_dump_sql) self.debug_menu.addAction(database_dump_sql) self.debug_menu.addSeparator() support_info = QMenu(self) support_info.setTitle('Supported Node Type') support_info.aboutToShow.connect(self.on_show_supported_type) self.debug_menu.addMenu(support_info)
def on_show_debug_menu(self): self.debug_menu.clear() if self.is_master_cmd or self.power_user: power_user_mode = QAction('Power User Mode', self) power_user_mode.setCheckable(True) power_user_mode.setChecked(MTTSettings.value('powerUser')) power_user_mode.triggered.connect(self.__on_toggle_power_user) self.debug_menu.addAction(power_user_mode) self.is_master_cmd = False self.debug_menu.addSeparator() open_pref_folder_action = QAction('Open Preferences Folder', self) open_pref_folder_action.setStatusTip('Open MTT preference folder') open_pref_folder_action.triggered.connect( self.on_open_preference_folder) self.debug_menu.addAction(open_pref_folder_action) self.debug_menu.addSeparator() database_dump_csv = QAction('Dump Database as CSV', self) database_dump_csv.triggered.connect(self.view.model.database_dump_csv) self.debug_menu.addAction(database_dump_csv) database_dump_sql = QAction('Dump Database as SQL', self) database_dump_sql.triggered.connect(self.view.model.database_dump_sql) self.debug_menu.addAction(database_dump_sql) self.debug_menu.addSeparator() support_info = QMenu(self) support_info.setTitle('Supported Node Type') support_info.aboutToShow.connect(self.on_show_supported_type) self.debug_menu.addMenu(support_info)
def updateFileMenu(self): """ Updates the file menu dynamically, so that recent files can be shown. """ self.menuFile.clear() # self.menuFile.addAction(self.actionNew) # disable for now self.menuFile.addAction(self.actionOpen) self.menuFile.addAction(self.actionSave) self.menuFile.addAction(self.actionSave_as) self.menuFile.addAction(self.actionClose_Model) recentFiles = [] for filename in self.recentFiles: if QFile.exists(filename): recentFiles.append(filename) if len(self.recentFiles) > 0: self.menuFile.addSeparator() for i, filename in enumerate(recentFiles): action = QAction("&%d %s" % (i + 1, QFileInfo(filename).fileName()), self) action.setData(filename) action.setStatusTip("Opens recent file %s" % QFileInfo(filename).fileName()) action.setShortcut(QKeySequence(Qt.CTRL | (Qt.Key_1 + i))) action.triggered.connect(self.load_model) self.menuFile.addAction(action) self.menuFile.addSeparator() self.menuFile.addAction(self.actionQuit)
def updateFileMenu(self): """ Updates the file menu dynamically, so that recent files can be shown. """ self.menuFile.clear() # self.menuFile.addAction(self.actionNew) # disable for now self.menuFile.addAction(self.actionOpen) self.menuFile.addAction(self.actionSave) self.menuFile.addAction(self.actionSave_as) self.menuFile.addAction(self.actionClose_Model) recentFiles = [] for filename in self.recentFiles: if QFile.exists(filename): recentFiles.append(filename) if len(self.recentFiles) > 0: self.menuFile.addSeparator() for i, filename in enumerate(recentFiles): action = QAction("&%d %s" % (i + 1, QFileInfo(filename).fileName()), self) action.setData(filename) action.setStatusTip("Opens recent file %s" % QFileInfo(filename).fileName()) action.setShortcut(QKeySequence(Qt.CTRL | (Qt.Key_1+i))) action.triggered.connect(self.load_model) #self.connect(action, SIGNAL("triggered()"), self.load_model) self.menuFile.addAction(action) self.menuFile.addSeparator() self.menuFile.addAction(self.actionQuit)
def addExitButton(self): """ Adds the Exit Button to the ToolBar """ exitAction = QAction(self.getQIcon('exit.png'), 'Exit the Application', self) exitAction.setShortcut('Ctrl+Q') exitAction.setStatusTip("Exit the Application.") exitAction.triggered.connect(QtCore.QCoreApplication.instance().quit) self.addAction(exitAction)
def addNewTransactionButton(self): """ Adds the New Transaction Button to the ToolBar """ newIcon = self.getQIcon('money.png') newTransactionAction = QAction(newIcon, 'New Transaction', self) newTransactionAction.setShortcut('Ctrl+N') newTransactionAction.setStatusTip("Create a New Transaction.") newTransactionAction.triggered.connect(self.newTransaction) self.addAction(newTransactionAction)
def add_action(lbl, tip, cmd, checkable=False, checked=False): a = QAction(lbl, self) a.setStatusTip(tip) a.triggered.connect(cmd) if checkable: a.setCheckable(True) a.setChecked(checked) return a
def add_action(lbl, tip, cmd, checkable=False, checked=False): a = QAction(lbl, self) a.setStatusTip(tip) a.triggered.connect(cmd) if checkable: a.setCheckable(True) a.setChecked(checked) return a
def buildExistingTransferSection(self): """ Build existing Transfer Section """ if self.toolbar.transaction.account is self.table_view.account: self.transferLabel = QLabel("Transferred {0}: {1}".format(self.getTransferDirection(), self.toolbar.transaction.transferAccount.name), self.toolbar) else: self.transferLabel = QLabel("Transferred {0}: {1}".format(self.getTransferDirection(), self.toolbar.transaction.account.name), self.toolbar) self.toolbar.addWidget(self.transferLabel) eraseIcon = self.toolbar.getQIcon('erase.png') removeTransferAction = QAction(eraseIcon, 'Remove Transfer', self.toolbar) removeTransferAction.setStatusTip("Remove Transfer.") removeTransferAction.triggered.connect(self.removeTransfer) self.toolbar.addAction(removeTransferAction)
def _createAction(self, text, slot=None, shortcut=None, icon=None, tip=None, checkable=False, signal="triggered"): action = QAction(text, self) if icon is not None: action.setIcon(QIcon(":/{0}.png".format(icon))) if shortcut is not None: action.setShortcut(shortcut) if tip is not None: action.setToolTip(tip) action.setStatusTip(tip) if slot is not None: getattr(action, signal).connect(slot) if checkable: action.setCheckable(True) return action
def init_ui(self): # geometry is x offset, y offset, x width, y width self.setGeometry(150, 150, 640, 300) self.setWindowTitle(self.title) menu_bar = self.menuBar() file_menu = menu_bar.addMenu('&File') exitAction = QAction('E&xit', self) exitAction.setStatusTip('Exit the application.') exitAction.triggered.connect(self.handle_exit) file_menu.addAction(exitAction) main_layout_container = QWidget() main_layout = QBoxLayout(QBoxLayout.TopToBottom) image_layout = QBoxLayout(QBoxLayout.LeftToRight) image_layout.addStretch(1) self.image1 = QLabel() self.image1.setAlignment(Qt.AlignCenter) image_layout.addWidget(self.image1) image_layout.addWidget(QLabel("vs.")) self.image2 = QLabel() self.image2.setAlignment(Qt.AlignCenter) image_layout.addWidget(self.image2) image_layout.addStretch(1) main_layout.addLayout(image_layout) main_layout.addStretch(1) button_layout = QBoxLayout(QBoxLayout.LeftToRight) button_layout.addStretch(1) self.yes_button = QPushButton("Yes") button_layout.addWidget(self.yes_button) self.yes_button.clicked.connect(self.handle_yes_pressed) self.no_button = QPushButton("No") button_layout.addWidget(self.no_button) self.no_button.clicked.connect(self.handle_no_pressed) button_layout.addStretch(1) main_layout.addLayout(button_layout) main_layout_container.setLayout(main_layout) self.image1_filepath = "" self.image2_filepath = "" self.load_more_images() self.setCentralWidget(main_layout_container)
def _createAction(self, name, slot, shortcut=None, statusTip=None): action = QAction(name, self) action.triggered.connect(slot) if shortcut is not None: action.setShortcut(shortcut) if statusTip is not None: action.setStatusTip(statusTip) key = _stripEllipsis(name) self._actions[key] = action return action
def createactions(self, text, slot=None, shortcut="None", icon=None, tip=None, checkable=False, signal="triggered()"): action = QAction(text, self) if icon is not None: action.setIcon(QIcon(icon)) if shortcut is not None: action.setShortcut(shortcut) if tip is not None: action.setToolTip(tip) action.setStatusTip(tip) if slot is not None: self.connect(action, SIGNAL(signal), slot) if checkable: action.setCheckable(True) return action
def __init__(self, parent=None): """Create Qt widgets, connect event handlers.""" super(App, self).__init__(parent) self.windowTitle = 'DMD | ' self.fileName = '' self.setWindowTitle(self.windowTitle + 'Unsaved File') exitAction = QAction('Exit', self) exitAction.setShortcut('Ctrl+Q') exitAction.setStatusTip('Exit application') exitAction.triggered.connect(self.close) openAction = QAction('Open', self) openAction.setShortcut('Ctrl+O') openAction.setStatusTip('Open Markdown File') openAction.triggered.connect(self.openFile) newAction = QAction('New', self) newAction.setShortcut('Ctrl+N') newAction.setStatusTip('New Markdown File') newAction.triggered.connect(self.newFile) saveAction = QAction('Save', self) saveAction.setShortcut('Ctrl+S') saveAction.setStatusTip('Save File') saveAction.triggered.connect(self.saveFile) self.statusBar() menubar = self.menuBar() fileMenu = menubar.addMenu('&File') fileMenu.addAction(newAction) fileMenu.addAction(openAction) fileMenu.addAction(saveAction) fileMenu.addAction(exitAction) self.setGeometry(300, 300, 1024, 768) self.show() self.txtInput = QTextEdit() self.txtInput.setTabStopWidth(20) self.webPreview = QWebView() self.webPreview.setHtml('Start typing...', baseUrl=QUrl('preview')) self.txtInput.textChanged.connect(self.loadPreview) splitter = QSplitter() splitter.addWidget(self.txtInput) splitter.addWidget(self.webPreview) self.setCentralWidget(splitter)
def __init__(self,fileName=None): """ Constructor Function """ # QWidget.__init__(self) # self.setWindowTitle("Icon Sample") # self.setGeometry(300, 300, 200, 150) QMainWindow.__init__(self) self.setWindowTitle("Icon Sample") self.setGeometry(300, 300, 200, 150) QToolTip.setFont(QFont("Decorative", 8, QFont.Bold)) self.setToolTip('Our Main Window') self.icon='C:\Users\Hamed\Documents\soheil sites image\imageedit__9411602959.gif' self.textEdit = QTextEdit() self.setCentralWidget(self.textEdit) self.fileName = None self.filters = "Text files (*.txt)" openFile = QAction(QIcon('open.png'), 'Open', self) openFile.setShortcut('Ctrl+O') openFile.setStatusTip('Open new File') openFile.triggered.connect(self.showDialog) menubar = self.menuBar() # fileMenu = menubar.addMenu('&File') # fileMenu.addAction(openFile) self.setGeometry(300, 300, 350, 300) self.setWindowTitle('Example - File Dialog') # self.myNameLE = QLineEdit(self) # self.myAgeLE = QLineEdit(self) # self.myChoiceLE = QLineEdit(self) self.statusLabel = QLabel('Showing Progress') self.progressBar = QProgressBar() self.progressBar.setMinimum(0) self.progressBar.setMaximum(100) ##################@@@@@@@@@@@@@@2 self.threads = [] self.addWorker(MyWorkerThread(1)) self.addWorker(MyWorkerThread(2)) #######################@@@@@@@@@@@@@ self.show()
def _parseactions(self, actions): actionlist = [] for act in actions: atts = actions[act] if act == "Separator": newaction = "Separator" else: try: newaction = QAction(QtGui.QIcon(atts["icon"]), atts["text"], self) except: newaction = QAction(atts["text"], self) try: newaction.setShortcut(atts["shortcut"]) except: pass try: newaction.setStatusTip(atts["statustip"]) except: pass actionlist.append((atts["pos"], newaction, act)) actionlist = self._sortbyposition(actionlist) return actionlist
def _parseactions(self, actions): actionlist = [] for act in actions: atts = actions[act] if act == "Separator": newaction = "Separator" else: try: newaction = QAction(QtGui.QIcon(atts["icon"]), atts["text"], self) except: newaction = QAction(atts["text"], self) try: newaction.setShortcut(atts["shortcut"]) except: pass try: newaction.setStatusTip(atts["statustip"]) except: pass actionlist.append((atts["pos"], newaction, act)) actionlist = self._sortbyposition(actionlist) return actionlist
def initUI(self): textEdit1 = QkLineView(sample=10) textEdit2 = QkLineView(sample=100) textEdit3 = QkLineView(sample=200) tabs = QTabWidget() tabs.addTab(textEdit1, "TAB1") tabs.addTab(textEdit2, "TAB2") tabs.addTab(textEdit3, "TAB3") tabs.setMovable(True) self.setCentralWidget(tabs) exitAct = QAction(QIcon(":pics/exit.PNG"), self.tr("Exit"), self) exitAct.setShortcut('Ctrl+Q') exitAct.setStatusTip(self.tr('Exit application')) exitAct.triggered.connect(self.close) self.statusBar() menubar = self.menuBar() fileMenu = menubar.addMenu(self.tr('&File')) fileMenu.addAction(exitAct) toolbar = self.addToolBar(self.tr('Exit')) toolbar.addAction(exitAct) toolbar.addAction(exitAct) self.setGeometry(300, 300, 350, 250) self.setWindowTitle(self.tr('binkeul main window')) self.show()
def __init__(self, parent=None): super(MainWindow, self).__init__(parent) # self.setObjectName("MainWindow") self.resize(731, 475) centralwidget = QWidget(self) # centralwidget.setObjectName("centralwidget") gridLayout = QGridLayout(centralwidget) # gridLayout.setObjectName("gridLayout") # textEdit needs to be a class variable. self.textEdit = QTextEdit(centralwidget) # self.textEdit.setObjectName("textEdit") gridLayout.addWidget(self.textEdit, 0, 0, 1, 1) self.setCentralWidget(centralwidget) menubar = QMenuBar(self) menubar.setGeometry(QRect(0, 0, 731, 29)) # menubar.setObjectName("menubar") menu_File = QMenu(menubar) # menu_File.setObjectName("menu_File") self.setMenuBar(menubar) statusbar = QStatusBar(self) # statusbar.setObjectName("statusbar") self.setStatusBar(statusbar) actionShow_GPL = QAction(self) # actionShow_GPL.setObjectName("actionShow_GPL") actionShow_GPL.triggered.connect(self.showGPL) action_About = QAction(self) # action_About.setObjectName("action_About") action_About.triggered.connect(self.about) iconToolBar = self.addToolBar("iconBar.png") #------------------------------------------------------ # Add icons to appear in tool bar - step 1 actionShow_GPL.setIcon(QIcon(":/showgpl.png")) action_About.setIcon(QIcon(":/about.png")) action_Close = QAction(self) action_Close.setCheckable(False) action_Close.setObjectName("action_Close") action_Close.setIcon(QIcon(":/quit.png")) #------------------------------------------------------ # Show a tip on the Status Bar - step 2 actionShow_GPL.setStatusTip("Show GPL Licence") action_About.setStatusTip("Pop up the About dialog.") action_Close.setStatusTip("Close the program.") #------------------------------------------------------ menu_File.addAction(actionShow_GPL) menu_File.addAction(action_About) menu_File.addAction(action_Close) menubar.addAction(menu_File.menuAction()) iconToolBar.addAction(actionShow_GPL) iconToolBar.addAction(action_About) iconToolBar.addAction(action_Close) action_Close.triggered.connect(self.close)
def __init__(self, parent=None): super(MainWindow, self).__init__(parent) # self.setObjectName("MainWindow") self.resize(731, 475) centralwidget = QWidget(self) # centralwidget.setObjectName("centralwidget") gridLayout = QGridLayout(centralwidget) # gridLayout.setObjectName("gridLayout") # textEdit needs to be a class variable. self.textEdit = QTextEdit(centralwidget) # self.textEdit.setObjectName("textEdit") gridLayout.addWidget(self.textEdit, 0, 0, 1, 1) self.setCentralWidget(centralwidget) menubar = QMenuBar(self) menubar.setGeometry(QRect(0, 0, 731, 29)) # menubar.setObjectName("menubar") menu_File = QMenu(menubar) # menu_File.setObjectName("menu_File") self.setMenuBar(menubar) statusbar = QStatusBar(self) # statusbar.setObjectName("statusbar") self.setStatusBar(statusbar) actionShow_GPL = QAction(self) # actionShow_GPL.setObjectName("actionShow_GPL") actionShow_GPL.triggered.connect(self.showGPL) action_About = QAction(self) # action_About.setObjectName("action_About") action_About.triggered.connect(self.about) iconToolBar = self.addToolBar("iconBar.png") #------------------------------------------------------ # Add icons to appear in tool bar - step 1 actionShow_GPL.setIcon(QIcon(":/showgpl.png")) action_About.setIcon(QIcon(":/about.png")) action_Close = QAction(self) action_Close.setCheckable(False) action_Close.setObjectName("action_Close") action_Close.setIcon(QIcon(":/quit.png")) #------------------------------------------------------ # Show a tip on the Status Bar - step 2 actionShow_GPL.setStatusTip("Show GPL Licence") action_About.setStatusTip("Pop up the About dialog.") action_Close.setStatusTip("Close the program.") #------------------------------------------------------ menu_File.addAction(actionShow_GPL) menu_File.addAction(action_About) menu_File.addAction(action_Close) menubar.addAction(menu_File.menuAction()) iconToolBar.addAction(actionShow_GPL) iconToolBar.addAction(action_About) iconToolBar.addAction(action_Close) action_Close.triggered.connect(self.close)
def _initUI(self,parent): "Adds the menu items into the menu bar" #File Menu #add action _addAction = QAction("Add Snippet", parent) _addAction.setShortcut("Ctrl+N") _addAction.setStatusTip('Add new Snippet') _addAction.triggered.connect(self._addSnippet) #edit action _editAction = QAction("Edit Snippet", parent) _editAction.setShortcut("Ctrl+O") _editAction.setStatusTip('Edit Snippet') _editAction.triggered.connect(self._editSnippet) #exit action _exitAction = QAction("&Exit", parent) _exitAction.setShortcut("Ctrl+Q") _exitAction.setStatusTip('Exit application') _exitAction.triggered.connect(parent.closeApp) # Adding to file menu _fileMenu = self.addMenu('&File') _fileMenu.addAction(_addAction) _fileMenu.addAction(_editAction) _fileMenu.addSeparator() _fileMenu.addAction(_exitAction) #Edit Menu #copy action _copyAction = QAction("&Copy", parent) _copyAction.setShortcut("Ctrl+C") _copyAction.setStatusTip('Copy text') _editMenu = self.addMenu('&Edit') _editMenu.addAction(_copyAction) #Tools _toolsMenu = self.addMenu('&Tools')
def Menu(self): #this creates an action exit, a shortcut and status tip exitAction = QAction(QIcon('icons/exit.png'), '&Exit', self) exitAction.setShortcut('Ctrl+Q') exitAction.setStatusTip('Exit application') exitAction.triggered.connect(self.close) openFile = QAction(QIcon('icons/open.png'), '&Open', self) openFile.setShortcut('Ctrl+O') openFile.setStatusTip('Open new File') openFile.triggered.connect(self.browse) runAction = QAction(QIcon('icons/run.png'), '&Run', self) runAction.setShortcut('Ctrl+R') runAction.setStatusTip('Run Mars') runAction.triggered.connect(self.run_event)
class MainWindow(QDialog): """monkey_linux UI""" def __init__(self,parent=None): super(MainWindow, self).__init__() self.init_conf() self.setParent(parent) common.Log.info("set up ui") self.setup_ui() self.findDeviceAction.triggered.connect(self.get_device_status) self.deleteDeviceAction.triggered.connect(self.del_device) # self.storeButton.clicked.connect(self.set_conf) self.startButton.clicked.connect(self.start) self.stopButton.clicked.connect(self.stop) self.checkLogButton.clicked.connect(self.check) self.monkeyButton.clicked.connect(self.checkMonkeyLog) self.exportButton.clicked.connect(self.exportConf) self.importButton.clicked.connect(self.importConf) self.setAbout.triggered.connect(self.about) self.startTime = datetime.datetime.now() self.secsTime = float(1) * 60 * 60 def setup_ui(self): # main window width hand height # self.setMinimumWidth(600) self.setMaximumWidth(800) self.setMinimumHeight(600) # main window title self.setWindowTitle(static.title) # file menu bar self.menuBar = QMenuBar() self.menuBar.setMaximumHeight(23) # self.menuFile = self.menuBar.addMenu(static.menuFile) # self.importAction = QAction(QIcon(static.importPNG), static.importFile, self) # self.exportAction = QAction(QIcon(static.exportPNG), static.exportFile, self) # self.menuFile.addAction(self.importAction) # self.menuFile.addAction(self.exportAction) self.setEnvActioin = QAction(QIcon(static.setPNG), static.pcSet, self) self.menuSet = self.menuBar.addMenu(static.menuSet) self.menuSet.addAction(self.setEnvActioin) self.setAbout = QAction(QIcon(static.setPNG), static.menuAbout, self) self.setAbout.setStatusTip('About') # 状态栏提示 self.menuHelp = self.menuBar.addMenu(static.menuHelp) self.menuHelp.addAction(self.setAbout) # set all layout self.hbox = QHBoxLayout(self) # device ======== self.topLeft = QFrame(self) self.topLeft.setMaximumSize(218, 300) self.topLeft.setMinimumSize(218, 200) self.topLeft.setFrameShape(QFrame.StyledPanel) self.topLeftLayout = QVBoxLayout(self.topLeft) self.toolBar = QToolBar() # self.androidDeviceAction = QRadioButton('Android', self) # self.androidDeviceAction.setFocusPolicy(Qt.NoFocus) # self.ipDeviceAction = QRadioButton('IP', self) # self.ipDeviceAction.setFocusPolicy(Qt.NoFocus) # self.ipDeviceAction.move(10, 10) # self.ipDeviceAction.toggle() self.findDeviceAction = QAction(QIcon(static.findDevice), static.findDeviceButton, self) self.deleteDeviceAction = QAction(QIcon(static.deleteDevice), static.deleteDeviceButton, self) # self.toolBar.addWidget(self.androidDeviceAction) # self.toolBar.addWidget(self.ipDeviceAction) self.toolBar.addAction(self.findDeviceAction) self.toolBar.addAction(self.deleteDeviceAction) self.deviceLab = QLabel(static.deviceName, self) self.device = QTableWidget(1, 2) self.device.setHorizontalHeaderLabels(['name', 'status']) self.device.setColumnWidth(0, 100) self.device.setColumnWidth(1, 80) self.topLeftLayout.addWidget(self.deviceLab) self.topLeftLayout.addWidget(self.toolBar) self.topLeftLayout.addWidget(self.device) # set button or other for running monkey or not and status of device and log ======== self.topRight = QFrame(self) self.topRight.setFrameShape(QFrame.StyledPanel) self.topRight.setMaximumHeight(40) self.startButton = QPushButton(QIcon(static.startPNG), "") self.stopButton = QPushButton(QIcon(static.stopPNG), "") self.status = QLabel(static.status) self.statusEdit = QLineEdit(self) self.statusEdit.setReadOnly(True) self.statusEdit.setMaximumWidth(80) self.statusEdit.setMinimumWidth(80) self.statusEdit.setText("") # check log self.checkLogButton = QPushButton(static.checkLog) self.checkLogButton.setMaximumHeight(20) self.checkLogButton.setMinimumHeight(20) self.checkLogButton.setMaximumWidth(60) self.selectLog = QLabel(static.selectlog) self.logfile = QComboBox() self.dirlist = os.listdir(os.path.join(DIR, "Result")) for d in self.dirlist: if d != "AutoMonkey.log": self.logfile.insertItem(0, d) self.logfile.setMaximumWidth(150) self.logfile.setMaximumHeight(20) self.logfile.setMinimumHeight(20) self.topLayout = QHBoxLayout(self.topRight) self.topLayout.addWidget(self.startButton) self.topLayout.addWidget(self.stopButton) self.topLayout.addWidget(self.status) self.topLayout.addWidget(self.statusEdit) self.topLayout.addWidget(self.selectLog) self.topLayout.addWidget(self.logfile) self.topLayout.addWidget(self.checkLogButton) # set parameter for monkey ======= self.midRight = QFrame(self) self.midRight.setMaximumSize(555, 200) self.midRight.setMinimumSize(555, 200) self.midRight.setFrameShape(QFrame.StyledPanel) self.midRightLayout = QVBoxLayout(self.midRight) self.subLayout0 = QVBoxLayout() self.subLayout1 = QVBoxLayout() self.subLayout2 = QHBoxLayout() self.subLayout3 = QVBoxLayout() self.subLayout4 = QVBoxLayout() self.subLayout5 = QHBoxLayout() self.subLayout6 = QHBoxLayout() self.toolBar = QToolBar() # self.storeAction = QAction(QIcon(static.storePNG), static.storeButton, self) self.startAction = QAction(QIcon(static.startPNG), static.startButton, self) self.stopAction = QAction(QIcon(static.stopPNG), static.stopButton, self) # self.toolBar.addAction(self.storeAction) self.toolBar.addAction(self.startAction) self.toolBar.addAction(self.stopAction) self.timeLongLbl = QLabel(static.timeString, self) self.timeLong = QLineEdit(self) self.timeLong.setMaximumWidth(100) self.timeLong.setMinimumWidth(100) self.timeLong.setPlaceholderText(static.timeLong) self.timeLongUnit = QLabel("H") self.etSetLbl = QLabel(static.eventTypeSet) self.etSet = QTableWidget(2, 2) self.etSet.setMaximumHeight(150) self.etSet.setHorizontalHeaderLabels(['option', 'value']) self.etSet.horizontalHeader().setStretchLastSection(True) self.etSet.setItem(0, 0, QTableWidgetItem("--throttle")) self.etSet.setItem(0, 1, QTableWidgetItem(str(static.eventType["--throttle"]))) # set event type percent self.etPercentLbl = QLabel(static.eventTpyePercent, self) self.etPercent = QTableWidget(2, 2) self.etPercent.setMaximumHeight(150) self.etPercent.setHorizontalHeaderLabels(['option', 'value']) self.etPercent.horizontalHeader().setStretchLastSection(True) self.etPercent.setItem(0, 0, QTableWidgetItem("--pct-touch")) self.etPercent.setItem(0, 1, QTableWidgetItem(str(static.eventPercent["--pct-touch"]))) self.etPercent.setItem(1, 0, QTableWidgetItem("--pct-motion")) self.etPercent.setItem(1, 1, QTableWidgetItem(str(static.eventPercent["--pct-motion"]))) # self.storeButton = QPushButton(QIcon(static.storePNG), static.storeButton) # self.storeButton.setToolTip(static.storeButton) self.exportButton = QPushButton(QIcon(static.exportPNG), static.exportFile) self.exportButton.setToolTip(static.exportFile) self.importButton = QPushButton(QIcon(static.importPNG), static.importFile) self.importButton.setToolTip(static.importFile) self.subLayout2.addWidget(self.timeLongLbl) self.subLayout2.addWidget(self.timeLong) self.subLayout2.addWidget(self.timeLongUnit) self.subLayout2.addWidget(QLabel(" " * 300)) # self.subLayout2.addWidget(self.storeButton) self.subLayout2.addWidget(self.exportButton) self.subLayout2.addWidget(self.importButton) self.subLayout0.addLayout(self.subLayout2) self.subLayout3.addWidget(self.etSetLbl) self.subLayout3.addWidget(self.etSet) self.subLayout4.addWidget(self.etPercentLbl) self.subLayout4.addWidget(self.etPercent) self.subLayout5.addLayout(self.subLayout0) self.subLayout6.addLayout(self.subLayout3) self.subLayout6.addLayout(self.subLayout4) self.midRightLayout.addLayout(self.subLayout5) self.midRightLayout.addLayout(self.subLayout6) # log ======== self.bottom = QFrame(self) self.bottom.setFrameShape(QFrame.StyledPanel) # log information self.logInfo = QLabel(static.logInfo) # information filter self.logFilter = QLabel(static.logFilter) self.monkeyButton = QPushButton(static.openMonkeyLog) self.combo = QComboBox() for i in range(len(static.logLevel)): self.combo.addItem(static.logLevel[i]) self.combo.setMaximumWidth(55) self.combo.setMaximumHeight(20) self.combo.setMinimumHeight(20) # information details self.bottomLayout = QVBoxLayout(self.bottom) self.subLayout = QHBoxLayout() self.subLayout.addWidget(self.logInfo) for i in range(10): self.subLayout.addWidget(QLabel("")) self.subLayout.addWidget(self.monkeyButton) self.subLayout.addWidget(self.logFilter) self.subLayout.addWidget(self.combo) self.bottomLayout.addLayout(self.subLayout) self.tabwidget = TabWidget() self.tabwidget.setMinimumHeight(100) self.bottomLayout.addWidget(self.tabwidget) # splitter mainWindow ++++++++++++++++++++++++++++++++++++ self.splitter2 = QSplitter(Qt.Vertical) self.splitter2.addWidget(self.topRight) self.splitter2.addWidget(self.midRight) self.splitter0 = QSplitter(Qt.Horizontal) self.splitter0.addWidget(self.topLeft) self.splitter0.addWidget(self.splitter2) self.splitter1 = QSplitter(Qt.Vertical) self.splitter1.addWidget(self.menuBar) self.splitter1.addWidget(self.splitter0) self.splitter1.addWidget(self.bottom) self.hbox.addWidget(self.splitter1) self.setLayout(self.hbox) self.show() def about(self): common.showDialog(static.menuAbout, static.dialogAbout) def init_conf(self): common.Log.info("init monkey conf") with open(monkeyConfFile, "w") as f: f.write("deviceList = []" + "\n") f.write("times = " + static.times + "\n") f.write("--throttle = " + static.eventType["--throttle"] + "\n") f.write("--pct-touch = " + static.eventPercent["--pct-touch"] + "\n") f.write("--pct-motion = " + static.eventPercent["--pct-motion"] + "\n") def setup_env(self): pass def _set_eventType(self, confFile): try: option = self.etSet.item(0, 0).text() value = self.etSet.item(0, 1).text() if value > "0": with open(confFile, 'a+') as f: f.write(option + " = " + value + "\n") except AttributeError, e: pass
def initUI(self): # textEdit = QTextEdit() # self.setCentralWidget(textEdit) # self.setStyleSheet("QGroupBox { border: 1px solid gray; padding: 5px;}"); # Action to quit program exitAction = QAction(QIcon(None), 'Quit', self) exitAction.setShortcut('Ctrl+Q') exitAction.setStatusTip('Exit application') exitAction.triggered.connect(self.close) # # Action to update device list # self.refreshAction = QAction(QIcon('img/reload.png'), 'Refresh', self) # self.refreshAction.setShortcut('F5') # self.refreshAction.setStatusTip('Refresh list of connected devices.') # self.refreshAction.triggered.connect(self.updateDeviceList) # Action to show program information helpAction = QAction(QIcon(None), 'Help', self) helpAction.setShortcut('F1') helpAction.triggered.connect(self.showHelpDialog) # Action to help aboutAction = QAction(QIcon(None), 'About', self) aboutAction.triggered.connect(self.showAboutDialog) self.statusBar() # Add the file menu menubar = self.menuBar() fileMenu = menubar.addMenu('&File') # fileMenu.addAction(self.refreshAction) fileMenu.addAction(exitAction) fileMenu = menubar.addMenu('&Help') fileMenu.addAction(helpAction) fileMenu.addAction(aboutAction) # # Add the toolbar # toolbar = self.addToolBar('Exit') # # toolbar.addAction(self.refreshAction) # toolbar.setMovable(False) # Add the main windows widgets self.deviceListWidget = DeviceList(self.programDeviceHandler, self.infoDeviceHandler, self.resetDeviceHandler) self.fileSelectorWidget = FileSelector() self.setStyleSheet(""" QStatusBar { border-top: 1px solid #CCC; } QToolBar { border-top: 1px solid #DDD; border-bottom: 1px solid #CCC; } """) gbox = QGroupBox("Connected USB devices:") gboxLayout = QVBoxLayout() gboxLayout.addWidget(self.deviceListWidget) gbox.setLayout(gboxLayout) self.refreshEvent = QTimer() self.refreshEvent.setInterval(1250) self.refreshEvent.timeout.connect(self.USBUpdate) self.refreshEvent.start() layout = QVBoxLayout() layout.addWidget(self.fileSelectorWidget) layout.addWidget(gbox) self.setCentralWidget(QWidget()) self.centralWidget().setLayout(layout) self.setMinimumSize(620, 700) self.setMaximumWidth(620) self.setWindowFlags(Qt.Window | Qt.WindowMinimizeButtonHint | Qt.WindowCloseButtonHint) self.setGeometry(300, 300, 350, 250) self.setWindowTitle('keyplus layout and firmware loader') self.show()
class MainWindow(QMainWindow): start_acq = Signal(str) start_rec = Signal(str) collect_frame = Signal(object) collect_threshed = Signal(object) def __init__(self, parent=None): ''' sets up the whole main window ''' #standard init super(MainWindow, self).__init__(parent) #set the window title self.setWindowTitle('Open Ephys Control GUI') self.window_height = 700 self.window_width = 1100 self.screen2 = QDesktopWidget().screenGeometry(0) self.move( self.screen2.left() + (self.screen2.width() - self.window_width) / 2., self.screen2.top() + (self.screen2.height() - self.window_height) / 2.) self.get_info() self.noinfo = True while self.noinfo: loop = QEventLoop() QTimer.singleShot(500., loop.quit) loop.exec_() subprocess.Popen('start %s' % open_ephys_path, shell=True) self.collect_frame.connect(self.update_frame) self.collect_threshed.connect(self.update_threshed) self.acquiring = False self.recording = False self.video_height = self.window_height * .52 self.video_width = self.window_width * .48 self.resize(self.window_width, self.window_height) #create QTextEdit window 'terminal' for receiving stdout and stderr self.terminal = QTextEdit(self) #set the geometry self.terminal.setGeometry( QRect(self.window_width * .02, self.window_height * .15 + self.video_height, self.video_width * .96, 150)) #make widgets self.setup_video_frames() self.setup_thresh_buttons() self.overlay = True #create thread and worker for video processing self.videoThread = QThread(self) self.videoThread.start() self.videoproc_worker = VideoWorker(self) self.videoproc_worker.moveToThread(self.videoThread) self.vt_file = None """""" """""" """""" """""" """""" """""" """""" """ set up menus """ """""" """""" """""" """""" """""" """""" """""" #create a QMenuBar and set geometry self.menubar = QMenuBar(self) self.menubar.setGeometry( QRect(0, 0, self.window_width * .5, self.window_height * .03)) #set the QMenuBar as menu bar for main window self.setMenuBar(self.menubar) #create a QStatusBar statusbar = QStatusBar(self) #set it as status bar for main window self.setStatusBar(statusbar) #create icon toolbar with default image iconToolBar = self.addToolBar("iconBar.png") #create a QAction for the acquire button self.action_Acq = QAction(self) #make it checkable self.action_Acq.setCheckable(True) #grab an icon for the button acq_icon = self.style().standardIcon(QStyle.SP_MediaPlay) #set the icon for the action self.action_Acq.setIcon(acq_icon) #when the button is pressed, call the Acquire function self.action_Acq.triggered.connect(self.Acquire) #create a QAction for the record button self.action_Record = QAction(self) #make it checkable self.action_Record.setCheckable(True) #grab an icon for the button record_icon = self.style().standardIcon(QStyle.SP_DialogYesButton) #set the icon for the action self.action_Record.setIcon(record_icon) #when the button is pressed, call advanced_settings function self.action_Record.triggered.connect(self.Record) #create QAction for stop button action_Stop = QAction(self) #grab close icon stop_icon = self.style().standardIcon(QStyle.SP_MediaStop) #set icon for action action_Stop.setIcon(stop_icon) #when button pressed, close window action_Stop.triggered.connect(self.Stop) #show tips for each action in the status bar self.action_Acq.setStatusTip("Start acquiring") self.action_Record.setStatusTip("Start recording") action_Stop.setStatusTip("Stop acquiring/recording") #add actions to icon toolbar iconToolBar.addAction(self.action_Acq) iconToolBar.addAction(self.action_Record) iconToolBar.addAction(action_Stop) # self.sort_button = QPushButton('Sort Now',self) # self.sort_button.setGeometry(QRect(self.window_width*.85,0,self.window_width*.15,self.window_height*.05)) # self.sort_button.clicked.connect(self.sort_now) #show the window if minimized by windows self.showMinimized() self.showNormal() """""" """""" """""" """""" """""" """""" """""" """""" """""" """""" "" """""" """""" """""" """""" """""" """""" """""" """""" """""" """""" "" #this function acts as a slot to accept 'message' signal @Slot(str) def print_message(self, message): ''' print stdout and stderr to terminal window ''' #move terminal cursor to end self.terminal.moveCursor(QTextCursor.End) #write message to terminal self.terminal.insertPlainText(message) def setup_thresh_buttons(self): ''' set up buttons for overlay/clearing thresh view ''' self.button_frame = QFrame(self) self.button_frame.setGeometry( QRect(self.window_width * .52, self.window_height * .13 + self.video_height, self.video_width * .98, 50)) button_layout = QHBoxLayout() self.button_frame.setLayout(button_layout) self.clear_button = QPushButton('Clear') self.overlay_button = QPushButton('Overlay') button_layout.addWidget(self.clear_button) button_layout.addWidget(self.overlay_button) self.clear_button.setEnabled(False) self.clear_button.clicked.connect(self.clear_threshed) self.overlay_button.setEnabled(False) self.overlay_button.clicked.connect(self.overlay_threshed) def setup_video_frames(self): ''' set up spots for playing video frames ''' filler_frame = np.zeros((360, 540, 3)) filler_frame = qimage2ndarray.array2qimage(filler_frame) self.raw_frame = QFrame(self) self.raw_label = QLabel() self.raw_label.setText('raw') self.raw_frame.setGeometry( QRect(self.window_width * .01, self.window_height * .15, self.video_width, self.video_height)) self.raw_frame raw_layout = QVBoxLayout() self.raw_frame.setLayout(raw_layout) raw_layout.addWidget(self.raw_label) self.threshed_frame = QFrame(self) self.threshed_label = QLabel() self.threshed_label.setText('Threshed') self.threshed_frame.setGeometry( QRect(self.window_width * .51, self.window_height * .15, self.video_width, self.video_height)) threshed_layout = QVBoxLayout() self.threshed_frame.setLayout(threshed_layout) threshed_layout.addWidget(self.threshed_label) self.label_frame = QFrame(self) self.label_frame.setGeometry( QRect(self.window_width * .01, self.window_height * .11, self.video_width * 2, 50)) self.label_rawlabel = QLabel() self.label_rawlabel.setText('Raw Video') self.label_threshedlabel = QLabel() self.label_threshedlabel.setText('Threshold View') label_layout = QHBoxLayout() self.label_frame.setLayout(label_layout) label_layout.addWidget(self.label_rawlabel) label_layout.addWidget(self.label_threshedlabel) self.raw_label.setPixmap(QPixmap.fromImage(filler_frame)) self.threshed_label.setPixmap(QPixmap.fromImage(filler_frame)) def Acquire(self): if self.action_Acq.isChecked(): self.vidbuffer = [] if self.recording: while 1: try: self.sock.send('StopRecord') self.sock.recv() except: continue break self.recording = False else: #create and start a thread to transport a worker to later self.workerThread = QThread(self) self.workerThread.start() #create a worker object based on Worker class and move it to our #worker thread self.worker = Worker(self) self.worker.moveToThread(self.workerThread) try: self.start_acq.disconnect() except: pass while 1: try: self.sock.send('StartAcquisition') self.sock.recv() except: continue break self.acquiring = True self.start_acq.connect(self.worker.acquire) self.start_acq.emit('start!') self.action_Acq.setEnabled(False) self.action_Record.setChecked(False) self.action_Record.setEnabled(True) record_icon = self.style().standardIcon(QStyle.SP_DialogYesButton) #set the icon for the action self.action_Record.setIcon(record_icon) def Record(self): if self.action_Record.isChecked(): if not self.acquiring: self.workerThread = QThread(self) self.workerThread.start() self.worker = Worker(self) self.worker.moveToThread(self.workerThread) try: self.start_rec.disconnect() except: pass while 1: try: self.sock.send('StartAcquisition') self.sock.recv() except: continue break while 1: try: self.sock.send('StartRecord') self.sock.recv() except: continue break self.vidbuffer = [] self.start_rec.connect(self.worker.acquire) self.recording = True self.start_rec.emit('start!') else: while 1: try: self.sock.send('StartRecord') self.sock.recv() except: continue break self.vidbuffer = [] self.recording = True record_icon = self.style().standardIcon(QStyle.SP_DialogNoButton) #set the icon for the action self.action_Record.setIcon(record_icon) self.action_Record.setEnabled(False) self.action_Acq.setChecked(False) self.action_Acq.setEnabled(True) def Stop(self): self.acquiring = False self.recording = False while 1: try: self.sock.send('isRecording') rec = self.sock.recv() except: continue break if rec == '1': while 1: try: self.sock.send('StopRecord') self.sock.recv() except: continue break self.action_Record.setEnabled(True) self.action_Record.setChecked(False) while 1: try: self.sock.send('isAcquiring') acq = self.sock.recv_string() except: continue break if acq == '1': while 1: try: self.sock.send('StopAcquisition') self.sock.recv() except: continue break self.action_Acq.setEnabled(True) self.action_Acq.setChecked(False) try: #open a csv file for saving tracking data with open(self.vt_file, 'a') as csvfile: #create a writer vidwriter = csv.writer(csvfile, dialect='excel-tab') #check if it's an empty file for row in self.vidbuffer: vidwriter.writerow(row) except: pass record_icon = self.style().standardIcon(QStyle.SP_DialogYesButton) #set the icon for the action self.action_Record.setIcon(record_icon) def update_frame(self, image): self.raw_label.setPixmap(QPixmap.fromImage(image)) def update_threshed(self, threshed_image): self.threshed_label.setPixmap(QPixmap.fromImage(threshed_image)) def clear_threshed(self): self.green_frame = np.zeros_like(self.green_frame) self.red_frame = np.zeros_like(self.red_frame) def overlay_threshed(self): if self.overlay: self.overlay = False elif not self.overlay: self.overlay = True # def sort_now(self): # # if self.recdir is not None: # os.chdir('./kilosort_control') # #create and show the main window # self.sort_frame = kilosort_control.sort_gui.MainWindow() # self.sort_frame.show() # # #set up stream for stdout and stderr based on outputStream class # self.outputStream = kilosort_control.sort_gui.outputStream() # #when outputStream sends messages, connect to appropriate function for # #writing to terminal window # self.outputStream.message.connect(self.sort_frame.print_message) # # #connect stdout and stderr to outputStream # sys.stdout = self.outputStream # sys.stderr = self.outputStream # # self.sort_frame.run_now(self.recdir) # # self.close() def get_info(self): self.info_window = QWidget() self.info_window.resize(400, 350) #set title self.info_window.setWindowTitle('Session Info') #give layout info_layout = QVBoxLayout(self.info_window) with open('info_fields.pickle', 'rb') as f: default_fields = pickle.load(f) f.close() #set label for pic_resolution setting experimenter_label = QLabel('Experimenter:') #make a QLineEdit box for displaying/editing settings experimenter = QComboBox(self.info_window) experimenter.setEditable(True) experimenter.addItems(default_fields['experimenter']) #add label and box to current window info_layout.addWidget(experimenter_label) info_layout.addWidget(experimenter) #set label for pic_resolution setting whose_animal_label = QLabel('Whose animal?') #make a QLineEdit box for displaying/editing settings whose_animal = QComboBox(self.info_window) whose_animal.setEditable(True) whose_animal.addItems(default_fields['whose_animal']) #add label and box to current window info_layout.addWidget(whose_animal_label) info_layout.addWidget(whose_animal) animal_number_label = QLabel('Animal number:') animal_number = QComboBox(self.info_window) animal_number.setEditable(True) animal_number.addItems(default_fields['animal_number']) info_layout.addWidget(animal_number_label) info_layout.addWidget(animal_number) session_number_label = QLabel('Session number:') session_number = QTextEdit(self.info_window) session_number.setText('1') info_layout.addWidget(session_number_label) info_layout.addWidget(session_number) session_type_label = QLabel('Session type:') session_type = QComboBox(self.info_window) session_type.setEditable(True) session_type.addItems(default_fields['session_type']) info_layout.addWidget(session_type_label) info_layout.addWidget(session_type) def save_info(self): info_fields = {} info_fields['experimenter'] = [ experimenter.itemText(i) for i in range(experimenter.count()) ] info_fields['whose_animal'] = [ whose_animal.itemText(i) for i in range(whose_animal.count()) ] info_fields['animal_number'] = [ animal_number.itemText(i) for i in range(animal_number.count()) ] info_fields['session_type'] = [ session_type.itemText(i) for i in range(session_type.count()) ] with open('info_fields.pickle', 'wb') as f: pickle.dump(info_fields, f, protocol=2) f.close() current_experimenter = str(experimenter.currentText()) current_whose_animal = str(whose_animal.currentText()) current_animal_number = str(animal_number.currentText()) current_session_number = str(session_number.toPlainText()) current_session_type = str(session_type.currentText()) recdir = data_save_dir + current_whose_animal + '/' + current_animal_number if not os.path.exists(recdir): os.makedirs(recdir) self.experiment_info = '###### Experiment Info ######\r\n' self.experiment_info += 'Experimenter: %s\r\n' % current_experimenter self.experiment_info += 'Whose animal? %s\r\n' % current_whose_animal self.experiment_info += 'Animal number: %s\r\n' % current_animal_number self.experiment_info += 'Session number: %s\r\n' % current_session_number self.experiment_info += 'Session type: %s\r\n' % current_session_type self.experiment_info = self.experiment_info.encode() config_file = config_path + '/' + current_animal_number + '.xml' if not os.path.exists(config_file): shutil.copy(default_config, config_file) tree = et.parse(config_file) root = tree.getroot() for child in root: if child.tag == 'CONTROLPANEL': child.attrib['recordPath'] = recdir.replace('/', '\\') tree.write(config_file) tree.write(default_config) self.info_window.close() self.noinfo = False ready_button = QPushButton('Ready!') ready_button.clicked.connect(lambda: save_info(self)) info_layout.addWidget(ready_button) self.info_window.show()
def __init__(self, parent=None): ''' sets up the whole main window ''' #standard init super(MainWindow, self).__init__(parent) #set the window title self.setWindowTitle('Open Ephys Control GUI') self.window_height = 700 self.window_width = 1100 self.screen2 = QDesktopWidget().screenGeometry(0) self.move( self.screen2.left() + (self.screen2.width() - self.window_width) / 2., self.screen2.top() + (self.screen2.height() - self.window_height) / 2.) self.get_info() self.noinfo = True while self.noinfo: loop = QEventLoop() QTimer.singleShot(500., loop.quit) loop.exec_() subprocess.Popen('start %s' % open_ephys_path, shell=True) self.collect_frame.connect(self.update_frame) self.collect_threshed.connect(self.update_threshed) self.acquiring = False self.recording = False self.video_height = self.window_height * .52 self.video_width = self.window_width * .48 self.resize(self.window_width, self.window_height) #create QTextEdit window 'terminal' for receiving stdout and stderr self.terminal = QTextEdit(self) #set the geometry self.terminal.setGeometry( QRect(self.window_width * .02, self.window_height * .15 + self.video_height, self.video_width * .96, 150)) #make widgets self.setup_video_frames() self.setup_thresh_buttons() self.overlay = True #create thread and worker for video processing self.videoThread = QThread(self) self.videoThread.start() self.videoproc_worker = VideoWorker(self) self.videoproc_worker.moveToThread(self.videoThread) self.vt_file = None """""" """""" """""" """""" """""" """""" """""" """ set up menus """ """""" """""" """""" """""" """""" """""" """""" #create a QMenuBar and set geometry self.menubar = QMenuBar(self) self.menubar.setGeometry( QRect(0, 0, self.window_width * .5, self.window_height * .03)) #set the QMenuBar as menu bar for main window self.setMenuBar(self.menubar) #create a QStatusBar statusbar = QStatusBar(self) #set it as status bar for main window self.setStatusBar(statusbar) #create icon toolbar with default image iconToolBar = self.addToolBar("iconBar.png") #create a QAction for the acquire button self.action_Acq = QAction(self) #make it checkable self.action_Acq.setCheckable(True) #grab an icon for the button acq_icon = self.style().standardIcon(QStyle.SP_MediaPlay) #set the icon for the action self.action_Acq.setIcon(acq_icon) #when the button is pressed, call the Acquire function self.action_Acq.triggered.connect(self.Acquire) #create a QAction for the record button self.action_Record = QAction(self) #make it checkable self.action_Record.setCheckable(True) #grab an icon for the button record_icon = self.style().standardIcon(QStyle.SP_DialogYesButton) #set the icon for the action self.action_Record.setIcon(record_icon) #when the button is pressed, call advanced_settings function self.action_Record.triggered.connect(self.Record) #create QAction for stop button action_Stop = QAction(self) #grab close icon stop_icon = self.style().standardIcon(QStyle.SP_MediaStop) #set icon for action action_Stop.setIcon(stop_icon) #when button pressed, close window action_Stop.triggered.connect(self.Stop) #show tips for each action in the status bar self.action_Acq.setStatusTip("Start acquiring") self.action_Record.setStatusTip("Start recording") action_Stop.setStatusTip("Stop acquiring/recording") #add actions to icon toolbar iconToolBar.addAction(self.action_Acq) iconToolBar.addAction(self.action_Record) iconToolBar.addAction(action_Stop) # self.sort_button = QPushButton('Sort Now',self) # self.sort_button.setGeometry(QRect(self.window_width*.85,0,self.window_width*.15,self.window_height*.05)) # self.sort_button.clicked.connect(self.sort_now) #show the window if minimized by windows self.showMinimized() self.showNormal() """""" """""" """""" """""" """""" """""" """""" """""" """""" """""" "" """""" """""" """""" """""" """""" """""" """""" """""" """""" """""" ""
def __init__(self, parent=None): super(MainWindow, self).__init__(parent) self.resize(800, 480) self.setWindowTitle('PySide GUI') #self.setWindowFlags(PySide.QtCore.Qt.FramelessWindowHint) self.wgHome, self.dcHome = self.createHomePage() # serial page self.wgSerial = QWidget(self) gridLayout = QGridLayout(self.wgSerial) self.lb1 = QLabel('serial page') self.lb2 = QLabel('label 2') self.lb3 = QLabel('label 3') gridLayout.addWidget(self.lb1, 0, 0) gridLayout.addWidget(self.lb2, 1, 0) gridLayout.addWidget(self.lb3, 2, 0) self.sw = QStackedWidget(self) self.sw.addWidget(self.wgHome) self.sw.addWidget(self.wgSerial) self.setCentralWidget(self.sw) menubar = QMenuBar(self) menubar.setGeometry(QRect(0, 0, 731, 29)) menu_File = QMenu(menubar) self.setMenuBar(menubar) statusbar = QStatusBar(self) self.setStatusBar(statusbar) actionHome = QAction(self) actionHome.setIcon(QIcon("icon/Home-50.png")) actionHome.setStatusTip("Home content") actionHome.triggered.connect( lambda: self.sw.setCurrentWidget(self.wgHome)) actionSerial = QAction(self) actionSerial.setIcon(QIcon("icon/Unicast-50.png")) actionSerial.setStatusTip("Serial polling task status") actionSerial.triggered.connect( lambda: self.sw.setCurrentWidget(self.wgSerial)) actionLogging = QAction(self) actionLogging.setIcon(QIcon("icon/Database-50.png")) actionLogging.setStatusTip("Logging task status") actionLogging.triggered.connect( lambda: self.sw.setCurrentWidget(self.wgLogging)) actionUpload = QAction(self) actionUpload.setIcon(QIcon("icon/Upload to Cloud-50.png")) actionUpload.setStatusTip("Uploading task status") actionUpload.triggered.connect( lambda: self.sw.setCurrentWidget(self.wgLogging)) actionDebug = QAction(self) actionDebug.setIcon(QIcon("icon/Bug-50.png")) actionDebug.setStatusTip("debug") actionDebug.triggered.connect(self.debug) actionAbout = QAction(self) actionAbout.triggered.connect(self.about) actionAbout.setIcon(QIcon("icon/Info-50.png")) actionAbout.setStatusTip("Pop up the About dialog.") actionSetting = QAction(self) actionSetting.setCheckable(False) actionSetting.setObjectName('action_clear') actionSetting.setIcon(QIcon("icon/Settings-50.png")) actionLeft = QAction(self) actionLeft.setIcon(QIcon("icon/Left-50.png")) actionLeft.setStatusTip("Left page") actionLeft.triggered.connect(self.switchLeftWidget) actionRight = QAction(self) actionRight.setIcon(QIcon("icon/Right-50.png")) actionRight.setStatusTip("Right page") actionRight.triggered.connect(self.switchRightWidget) actionClose = QAction(self) actionClose.setCheckable(False) actionClose.setObjectName("action_Close") actionClose.setIcon(QIcon("icon/Delete-50.png")) actionClose.setStatusTip("Close the program.") actionClose.triggered.connect(self.close) #------------------------------------------------------ menu_File.addAction(actionHome) menu_File.addAction(actionAbout) menu_File.addAction(actionClose) menu_File.addAction(actionSetting) menubar.addAction(menu_File.menuAction()) iconToolBar = self.addToolBar("iconBar.png") iconToolBar.addAction(actionHome) iconToolBar.addAction(actionSerial) iconToolBar.addAction(actionLogging) iconToolBar.addAction(actionUpload) iconToolBar.addAction(actionDebug) iconToolBar.addAction(actionAbout) iconToolBar.addAction(actionSetting) iconToolBar.addAction(actionLeft) iconToolBar.addAction(actionRight) iconToolBar.addAction(actionClose)
class EditorWindow(QMainWindow): """initialize editor""" def __init__(self, tixi, xmlFilename, cpacs_scheme=Config.path_cpacs_21_schema): super(EditorWindow, self).__init__() self.cur_file_path = "" self.cur_schema_path = "" self.setupEditor() self.setupButtonMenu() self.setupSearchBox() self.setupStatusbar() self.setupMenubar() self.setupNumbar() self.popUpWidget = None self.flag_layout = False self.hbox = QHBoxLayout() self.hbox.setSpacing(0) self.hbox.setContentsMargins(0,0,0,0) self.hbox.addWidget(self.number_bar) self.hbox.addWidget(self.editor) self.layout = QGridLayout() self.layout.addWidget(self.searchbox, 0, 0, 1, 4) self.layout.addWidget(self.button1, 0, 4, 1, 1) self.layout.addWidget(self.button2, 0, 5, 1, 1) self.layout.addLayout(self.hbox, 2, 0, 1, 8) self.layout.addWidget(self.fontsizeSpinBox, 0, 6, 1, 1) self.layout.addWidget(self.label1, 0, 7, 1, 1) self.window = QWidget() self.window.setLayout(self.layout) self.setWindowTitle('Simple XML editor') self.setCentralWidget(self.window) self.resize(800, 800) self.show() self.tixi = tixi self.loadFile(xmlFilename, cpacs_scheme) ''' loads cpacs file and validates it against the cpacs_schema @param xmlFilename: input file @param cpacs_scheme: validation scheme ''' def loadFile(self, xmlFilename=None, cpacs_scheme=Config.path_cpacs_21_schema): if xmlFilename and cpacs_scheme : try: self.tixi.open(xmlFilename) #self.tixi.openDocument(xmlFilename) #self.tixi.schemaValidateFromFile(cpacs_scheme) self.editor.setPlainText(self.tixi.exportDocumentAsString()) self.cur_file_path = xmlFilename self.cur_schema_path = cpacs_scheme except TixiException as e: self.statusBar().showMessage('CPACS ERROR: ' + e.error) ''' update the dictionary by the cpacs scheme @param path_dict: path to directory @param path_scheme: path to cpacs_scheme ''' def updatedictionary(self, path_dict=Config.path_code_completion_dict, path_scheme=Config.path_cpacs_21_schema): found = False olddict = open(path_dict) scheme_file = open(path_scheme, 'r') with open(path_dict, "a") as newdict : for line in scheme_file : word = re.search("(?<=\<xsd:complexType name=\").*(?=\"\>)", line) if word != None : for tmp in olddict : if tmp == word.group(0) +"\n" : found = True break if(not found) : newdict.write(word.group(0)+"\n") olddict.seek(0) found = False olddict.close() newdict.close() scheme_file.close() ''' validate xml file and write result to statusBar ''' def validate(self): try: etree.fromstring(str(self.editor.toPlainText())) self.statusBar().showMessage("Valid XML") except etree.XMLSyntaxError as e: if e.error_log.last_error is not None: msg = e.error_log.last_error.message line = e.error_log.last_error.line col = e.error_log.last_error.column self.statusBar().showMessage("Invalid XML: Line %s, Col %s: %s"%(line,col,msg)) except: self.statusBar().showMessage("Invalid XML: Unknown error") ''' close and cleanup tixi ''' def __del__(self): pass #self.tixi.close() #self.tixi.cleanup() ''' set and connect the search buttons ''' def setupButtonMenu(self): self.button1 = QPushButton("previous" ) self.button2 = QPushButton("next" ) self.label1 = QLabel("font") self.fontsizeSpinBox = QSpinBox() self.button1.hide() self.button2.hide() self.label1.hide() self.fontsizeSpinBox.hide() self.button1.clicked.connect(self.fire_search_backward) self.button2.clicked.connect(self.fire_search_foreward) self.fontsizeSpinBox.setRange(4, 30) self.fontsizeSpinBox.setSingleStep(1) self.fontsizeSpinBox.setSuffix('pt') self.fontsizeSpinBox.setValue(10) self.fontsizeSpinBox.valueChanged.connect(self.setfontsize) def setfontsize(self, value): self.font.setPointSize(value) self.editor.setFont(self.font) def setupEditor(self): self.font = QFont() self.font.setFamily('Courier') self.font.setFixedPitch(True) self.font.setPointSize(10) self.editor = EditorCodeCompletion(Config().path_code_completion_dict) self.editor.setFont(self.font) self.editor.setTabStopWidth(20) self.editor.setAcceptRichText(False) self.editor.setLineWrapMode(QTextEdit.NoWrap) self.editor.textChanged.connect(self.validate) self.highlighter = Highlighter(self.editor.document()) def setupNumbar(self): self.number_bar = NumberBar() self.number_bar.setTextEdit(self.getStates()) self.editor.cursorPositionChanged.connect(self.fireUpdateNumbar) self.connect(self.editor.verticalScrollBar(), SIGNAL("valueChanged(int)"), self.fireUpdateNumbar) #self.editor.verticalScrollBar.valueChanged.connect(self.fireUpdateNumbar) def setupStatusbar(self): self.lineNumber = -1 self.colNumber = -1 self.m_statusRight = QLabel("row: " + str(self.lineNumber) + ", col:" + str(self.colNumber), self) self.statusBar().addPermanentWidget(self.m_statusRight, 0) def setupSearchBox(self): self.searchbox = SearchField() self.searchbox.hide() def setupMenubar(self): commentAction = QAction('Comment', self) commentAction.setShortcut('Ctrl+K') commentAction.setStatusTip('Comment Block') commentAction.triggered.connect(self.fireComment) uncommentAction = QAction('Uncomment', self) uncommentAction.setShortcut('Ctrl+Shift+K') uncommentAction.setStatusTip('Comment Block') uncommentAction.triggered.connect(self.fireUnComment) searchAction = QAction('search', self) searchAction.setShortcut('Ctrl+F') searchAction.setStatusTip('search') searchAction.triggered.connect(self.fireSearchView) newAction = QAction('New', self) newAction.setShortcut('Ctrl+N') newAction.setStatusTip('creats empty cpacs-file') newAction.triggered.connect(self.fireNewAction) self.updateAction = QAction('Update', self) self.updateAction.setShortcut('Ctrl+U') self.updateAction.setStatusTip('Update CPACS') self.updateAction.triggered.connect(self.fireUpdate) revertAction = QAction('Revert', self) revertAction.setShortcut('Ctrl+R') revertAction.triggered.connect(self.fireRevert) clearAction = QAction('Clear', self) clearAction.setStatusTip('Clear Editor') clearAction.triggered.connect(self.editor.clear) numbarAction = QAction('Line Number', self) numbarAction.triggered.connect(self.fireSwitchLayout) self.xpathAction = QAction('Current XPath', self) self.xpathAction.triggered.connect(self.getCursorXPath) link_to_node_YesAction = QAction('yes', self) link_to_node_YesAction.triggered.connect(self.dummyFuction) link_to_node_NoAction = QAction('no', self) link_to_node_NoAction.triggered.connect(self.dummyFuction) toolXAction = QAction('Tool X',self) toolXAction.triggered.connect(self.fireToolX) menubar = self.menuBar() filemenu = menubar.addMenu("File") filemenu.addAction(newAction) filemenu.addAction(self.updateAction) filemenu.addAction(revertAction) sourcemenu = menubar.addMenu("Source") sourcemenu.addAction(commentAction) sourcemenu.addAction(uncommentAction) sourcemenu.addAction(searchAction) editormenu = menubar.addMenu("Editor") editormenu.addAction(clearAction) editormenu.addSeparator() editormenu.addAction(numbarAction) editormenu.addAction(self.xpathAction) editormenu_child1 = editormenu.addMenu('Link to node') editormenu_child1.addAction(link_to_node_YesAction) editormenu_child1.addAction(link_to_node_NoAction) toolmenu = menubar.addMenu("Tools") toolmenu.addAction(toolXAction) self.editor.setContextMenuPolicy(Qt.CustomContextMenu) self.editor.customContextMenuRequested.connect(self.showMenu) #self.editor.connect(self.editor, SIGNAL( "customContextMenuRequested(QPoint)" ), self.showMenu ) def showMenu( self, pos ): """ Show a context menu for the active layer in the legend """ menu = self.editor.createStandardContextMenu() menu.addAction(self.xpathAction) menu.exec_(QtCore.QPoint( self.mapToGlobal( pos ).x() + 5, self.mapToGlobal( pos ).y() )) def fireUpdateNumbar(self): self.updateLineNumber() self.number_bar.update() def dummyFuction(self): print ("not implemented yet") def getStates(self): self.stats = { "searchbox":self.searchbox, "editor":self.editor} return self.stats ''' find previous button ''' def fire_search_backward(self): self.editor.find(self.searchbox.text(), QTextDocument.FindBackward) self.searchbox.setFocus() ''' find next button ''' def fire_search_foreward(self): #print self.tixi.getNumberOfChilds('/cpacs/vehicles/aircraft/model[@uID="Aircraft1"]/wings/wing[@uID="Aircraft1_Wing1"]/transformation[@uID="Aircraft1_Wing1_Transf"]/scaling[@uID="Aircraft1_Wing1_Transf_Sca"]/z') searchList = list(filter(lambda a : a!='', self.searchbox.text().split('/'))) if len(searchList) == 1 : if self.editor.find(searchList[0]) : pass elif not self.editor.find(searchList[0], QTextDocument.FindBackward): QMessageBox.about(self, "error", "String %s not found" % (searchList[0])) else : self.editor.moveCursor(QTextCursor.Start) self.editor.find(searchList[0]) else : self.searchXPath(self.searchbox.text(), searchList) self.searchbox.setFocus() # test # /cpacs/vehicles/aircraft/model/wings/wing/sections/section def searchXPath(self, path, searchList): try: if self.tixi.xPathEvaluateNodeNumber(path) > 1 : QMessageBox.about(self, "error", "XPath %s not unique" % path) return self.editor.moveCursor(QTextCursor.Start) found = True # search index snd loop j = 0 # search backwards for uid for i in range(len(searchList)-1, -1, -1) : if '[' in searchList[i] : # get value in brackets : [x] --> x uid = re.search(r'\[(.*)\]', searchList[i]).group(1) uid = self.__transToSearchUid(searchList[:i+1], uid) found = self.editor.find(uid) j = i+1 break # search forward for all nodes after last uid while found and j < len(searchList) : found = self.editor.find('<'+searchList[j]) j += 1 if not found : QMessageBox.about(self, "error", "XPath %s not found" % path) except TixiException : QMessageBox.about(self, "error", "XPath %s not found" % path) def __transToSearchUid(self, path_list, uid): try: int(uid) path = "" for p in path_list : path = path + '/' + p return self.tixi.getTextAttribute(path , 'uID') except ValueError: return uid.replace('@', '') def getCursorXPath(self): start_pos = self.editor.textCursor().position() tag , tag_pos , isCursorInTag = self.getTagNameAtCursor() _,xpath_idx, xpath_uid = self.__findXPath_rec('/cpacs', '/cpacs' , tag, tag_pos) if not isCursorInTag: xpath_idx = self.__strRemoveReverseToChar(xpath_idx, '/') xpath_uid = self.__strRemoveReverseToChar(xpath_uid, '/') self.__setCursorToPostion(start_pos) self.__startXPathPopUp(xpath_idx, xpath_uid) def getTagNameAtCursor(self): ''' @return: name of tag , position of tag , cursor is btw open and closing tag ''' self.editor.find('<', QTextDocument.FindBackward) isClosingTag , fst_tag = self.__getTagName() pos = self.editor.textCursor().position() if isClosingTag : # find open tag of this closing tag self.editor.find('<'+fst_tag, QTextDocument.FindBackward) pos = self.editor.textCursor().position() return fst_tag , pos , False else: return fst_tag , pos , True def __getTagName(self): tc = self.editor.textCursor() tc.select(QTextCursor.WordUnderCursor) tx = tc.selectedText() isClosingTag = False if "</" in tx : # select next word tc.select(QTextCursor.WordUnderCursor) tx = tc.selectedText() isClosingTag = True return isClosingTag , "" if "<" in tx else tx def __findXPath_rec(self, xpath_idx, xpath_uid, search, pos): nodes = self.__getChildNodesIdxTuple(xpath_idx) for (node, idx) in nodes: if node != '#text' : new_xpath_idx, new_xpath_uid = self.__createNewXPath(xpath_idx, xpath_uid, node, idx) if search == node and self.isNodeAtSearchedTagPosition(new_xpath_uid, pos) : print ("gefunden" , new_xpath_idx) return True, new_xpath_idx , new_xpath_uid else: flag , res_idx, res_uid = self.__findXPath_rec(new_xpath_idx, new_xpath_uid, search, pos) if flag : return True, res_idx, res_uid return False , xpath_idx , xpath_uid def __getChildNodesIdxTuple(self, xpath): n = self.tixi.getNumberOfChilds(xpath) + 1 node_list = list(map(lambda i : self.tixi.getChildNodeName(xpath, i), range(1,n))) res = [] for j in range(len(node_list)) : cnt = 1 for k in range(j): if node_list[k] == node_list[j] : cnt = cnt + 1 res.append((node_list[j],cnt)) return res def __createNewXPath(self, xpath_idx, xpath_uid, node, idx): path_idx = xpath_idx + '/' + node path_uid = xpath_uid + '/' + node try : uID = self.tixi.getTextAttribute(path_idx + '[' + str(idx) + ']', 'uID') path_idx = path_idx + '[' + str(idx) + ']' path_uid = path_uid+'[@uID="' + uID + '"]' except TixiException: pass # e.error == 'ATTRIBUTE_NOT_FOUND return path_idx , path_uid def isNodeAtSearchedTagPosition(self, xpath, pos): ''' @param xpath: xpath with uids (doesn't work with indices) @param param: ''' self.editor.moveCursor(QTextCursor.Start) # split string at / and remove all empty strings l = list(filter(lambda x : x != '' , xpath.split('/'))) # search index snd loop j = 0 # search backwards for uid for i in range(len(l)-1, -1, -1) : if '[' in l[i] : # get value in brackets : [x] --> x uid = re.search(r'\[@(.*)\]', l[i]).group(1) self.editor.find(uid) j = i+1 break # search forward for all nodes after last uid while j < len(l) : self.editor.find('<'+l[j]) j += 1 return pos <= self.editor.textCursor().position() def __setCursorToPostion(self, pos): tc = self.editor.textCursor() tc.setPosition(pos) self.editor.setTextCursor(tc) def __startXPathPopUp(self, xpath_idx, xpath_uid): self.popUpWidget = XPathDialog(xpath_idx, xpath_uid) self.setEnabled(False) self.popUpWidget.closeAct.triggered.connect(self.__resetPopUpWidget) self.popUpWidget.show() def updateLineNumber(self): ''' sets the line and column number ''' self.lineNumber = self.editor.textCursor().blockNumber() + 1 self.colNumber = self.editor.textCursor().columnNumber() + 1 self.m_statusRight.setText("row: " + str(self.lineNumber) + ", col:" + str(self.colNumber)) def highlightCurrentLine(self) : ''' highlight line under cursor ''' extraSelections = [] selection = QTextEdit.ExtraSelection() lineColor = QColor(255, 250, 205) selection.format.setBackground(lineColor) selection.format.setProperty(QTextFormat.FullWidthSelection, True) selection.cursor = self.editor.textCursor() selection.cursor.clearSelection() extraSelections.append(selection) self.editor.setExtraSelections(extraSelections) self.editor.setFocus() #TODO: implemnt def fireUpdate(self): print ('dummy function - update the model') text_file = open(Config.path_cpacs_tmp_file, "w") text_file.write(self.editor.toPlainText()) text_file.close() #self.tixi.saveDocument(Config.path_cpacs_tmp_file) # '../cpacs_files/temp.xml' def fireRevert(self): ''' reloads cpacs file if not updated yet ''' if(self.cur_file_path and self.cur_schema_path) : self.loadFile(self.cur_file_path, self.cur_schema_path) else : QMessageBox.about(self, "error", "CPACS-File or Validation-Schema not available") def fireSwitchLayout(self): ''' function to show or hide line numbers ''' if(self.flag_layout) : self.number_bar.flag_show_numbers = True self.update() else : self.number_bar.flag_show_numbers = False self.update() self.flag_layout = not self.flag_layout def fireNewAction(self): ''' opens new file input form ''' self.setEnabled(False) self.popUpWidget = NewFileDialog() self.popUpWidget.buttonBox.accepted.connect(self.__createNewCpacsFile) self.popUpWidget.buttonBox.rejected.connect(self.__resetPopUpWidget) self.popUpWidget.closeAct.triggered.connect(self.__resetPopUpWidget) self.popUpWidget.show() def fireToolX(self): self.popUpWidget = ToolX("X-Tool", self.tixi) self.setEnabled(False) self.popUpWidget.buttonBox.accepted.connect(self.__resetPopUpWidget) self.popUpWidget.buttonBox.rejected.connect(self.__resetPopUpWidget) # closeAct for pressing X to close window self.popUpWidget.closeAct.triggered.connect(self.__resetPopUpWidget) self.popUpWidget.show() def __createNewCpacsFile(self): ''' closes all documents and creates new empty cpacs temporary file ''' idict = self.popUpWidget.fire_submitInput() self.tixi.closeAllDocuments() self.tixi.create('cpacs') self.tixi.addCpacsHeader(idict['name'], idict['creator'], idict['version'], idict['description'], idict['cpacsVersion']) self.tixi.saveDocument(Config.path_cpacs_tmp_file) self.loadFile(Config.path_cpacs_tmp_file) self.__resetPopUpWidget() def __resetPopUpWidget(self): self.popUpWidget.close() self.popUpWidget = None self.setEnabled(True) def fireComment(self): ''' inserts open respective closing tag before and after a selected text. ''' tc = self.editor.textCursor() tc.beginEditBlock() tc.setPosition(self.editor.textCursor().selectionStart()) tc.insertText("<!--") tc.setPosition(self.editor.textCursor().selectionEnd()) tc.insertText("-->") tc.endEditBlock() def fireUnComment(self): ''' removes open respective closing tag before and after a selected text. ''' tc = self.editor.textCursor() selectTxt = tc.selectedText() if selectTxt.find('<!--') != -1 : if selectTxt.rfind('-->') != -1 : selectTxt = selectTxt.replace('<!--', '', 1) selectTxt = self.__rreplace(selectTxt, '-->' , '', 1) tc.insertText(selectTxt) else: QMessageBox.about(self, "error", "no open tag (%s) in selection" % ('-->')) else: QMessageBox.about(self, "error", "no close tag (%s) in selection" % ('<!--')) def fireSearchView(self): ''' show and hide searchbox and buttons ''' if self.searchbox.isFocused() : self.searchbox.hide() self.button1.hide() self.button2.hide() self.label1.hide() self.fontsizeSpinBox.hide() else : self.searchbox.show() self.button1.show() self.button2.show() self.label1.show() self.fontsizeSpinBox.show() self.searchbox.setFocus() def keyPressEvent(self,event): ''' handle for searching strings by pressing enter key ''' if self.searchbox.isFocused() and event.key() == Qt.Key_Return : self.fire_search_foreward() # ====================================================================================================================== # utilities # ====================================================================================================================== def __strRemoveReverseToChar(self, s, c): return self.__rm_rec(s, c) def __rm_rec(self, s, c): if s == "" : return "" elif s[-1] == c : return s[:-1] else : return self.__rm_rec(s[:-1], c) def __rreplace(self, s, old, new, occurrence): ''' reverse string replace function @param s: source string @param old: char to be replaced @param new: new char @param occurrence: only the given count occurrences are replaced. ''' li = s.rsplit(old, occurrence) return new.join(li)
def setupMenubar(self): commentAction = QAction('Comment', self) commentAction.setShortcut('Ctrl+K') commentAction.setStatusTip('Comment Block') commentAction.triggered.connect(self.fireComment) uncommentAction = QAction('Uncomment', self) uncommentAction.setShortcut('Ctrl+Shift+K') uncommentAction.setStatusTip('Comment Block') uncommentAction.triggered.connect(self.fireUnComment) searchAction = QAction('search', self) searchAction.setShortcut('Ctrl+F') searchAction.setStatusTip('search') searchAction.triggered.connect(self.fireSearchView) newAction = QAction('New', self) newAction.setShortcut('Ctrl+N') newAction.setStatusTip('creats empty cpacs-file') newAction.triggered.connect(self.fireNewAction) self.updateAction = QAction('Update', self) self.updateAction.setShortcut('Ctrl+U') self.updateAction.setStatusTip('Update CPACS') self.updateAction.triggered.connect(self.fireUpdate) revertAction = QAction('Revert', self) revertAction.setShortcut('Ctrl+R') revertAction.triggered.connect(self.fireRevert) clearAction = QAction('Clear', self) clearAction.setStatusTip('Clear Editor') clearAction.triggered.connect(self.editor.clear) numbarAction = QAction('Line Number', self) numbarAction.triggered.connect(self.fireSwitchLayout) self.xpathAction = QAction('Current XPath', self) self.xpathAction.triggered.connect(self.getCursorXPath) link_to_node_YesAction = QAction('yes', self) link_to_node_YesAction.triggered.connect(self.dummyFuction) link_to_node_NoAction = QAction('no', self) link_to_node_NoAction.triggered.connect(self.dummyFuction) toolXAction = QAction('Tool X',self) toolXAction.triggered.connect(self.fireToolX) menubar = self.menuBar() filemenu = menubar.addMenu("File") filemenu.addAction(newAction) filemenu.addAction(self.updateAction) filemenu.addAction(revertAction) sourcemenu = menubar.addMenu("Source") sourcemenu.addAction(commentAction) sourcemenu.addAction(uncommentAction) sourcemenu.addAction(searchAction) editormenu = menubar.addMenu("Editor") editormenu.addAction(clearAction) editormenu.addSeparator() editormenu.addAction(numbarAction) editormenu.addAction(self.xpathAction) editormenu_child1 = editormenu.addMenu('Link to node') editormenu_child1.addAction(link_to_node_YesAction) editormenu_child1.addAction(link_to_node_NoAction) toolmenu = menubar.addMenu("Tools") toolmenu.addAction(toolXAction) self.editor.setContextMenuPolicy(Qt.CustomContextMenu) self.editor.customContextMenuRequested.connect(self.showMenu)
def createAction(self, icon, toolTip, statusTip, scripted=False): """ TOWRITE :param `icon`: TOWRITE :type `icon`: QString :param `toolTip`: TOWRITE :type `toolTip`: QString :param `statusTip`: TOWRITE :type `statusTip`: QString :param `scripted`: TOWRITE :type `scripted`: bool :rtype: `QAction`_ .. TODO:: send the global Icon, Image, Commands Dirs in to be used. """ connect = self.connect # NOT local optimization, but for ease of the code looking similar to the C++ whash mdiArea = self.mdiArea # ditto ACTION = QAction( QIcon(self.gIconDir + os.sep + self.getSettingsGeneralIconTheme() + "/" + icon + ".png"), toolTip, self ) # QAction * # TODO: Qt4.7 wont load icons without an extension... ACTION.setStatusTip(statusTip) ACTION.setObjectName(icon) # TODO: Set What's This Context Help to statusTip for now so there is some infos there. # Make custom whats this context help popup with more descriptive help than just # the status bar/tip one liner(short but not real long) with a hyperlink in the custom popup # at the bottom to open full help file description. Ex: like wxPython AGW's SuperToolTip. ACTION.setWhatsThis(statusTip) # TODO: Finish All Commands ... <.< if icon == "donothing": connect(ACTION, SIGNAL("triggered()"), self, SLOT("doNothing()")) elif icon == "new": ACTION.setShortcut(QKeySequence.New) connect(ACTION, SIGNAL("triggered()"), self, SLOT("newFile()")) elif icon == "open": ACTION.setShortcut(QKeySequence.Open) connect(ACTION, SIGNAL("triggered()"), self, SLOT("openFile()")) elif icon == "save": ACTION.setShortcut(QKeySequence.Save) connect(ACTION, SIGNAL("triggered()"), self, SLOT("savefile()")) elif icon == "saveas": ACTION.setShortcut(QKeySequence.SaveAs) connect(ACTION, SIGNAL("triggered()"), self, SLOT("saveasfile()")) elif icon == "print": ACTION.setShortcut(QKeySequence.Print) connect(ACTION, SIGNAL("triggered()"), self, SLOT("print_()")) elif icon == "designdetails": ACTION.setShortcut(QKeySequence("Ctrl+D")) connect(ACTION, SIGNAL("triggered()"), self, SLOT("designDetails()")) elif icon == "exit": ACTION.setShortcut(QKeySequence("Ctrl+Q")) connect(ACTION, SIGNAL("triggered()"), self, SLOT("exit()")) elif icon == "cut": ACTION.setShortcut(QKeySequence.Cut) connect(ACTION, SIGNAL("triggered()"), self, SLOT("cut()")) elif icon == "copy": ACTION.setShortcut(QKeySequence.Copy) connect(ACTION, SIGNAL("triggered()"), self, SLOT("copy()")) elif icon == "paste": ACTION.setShortcut(QKeySequence.Paste) connect(ACTION, SIGNAL("triggered()"), self, SLOT("paste()")) elif icon == "windowcascade": connect(ACTION, SIGNAL("triggered()"), mdiArea, SLOT("cascade()")) elif icon == "windowtile": connect(ACTION, SIGNAL("triggered()"), mdiArea, SLOT("tile()")) elif icon == "windowclose": ACTION.setShortcut(QKeySequence.Close) connect(ACTION, SIGNAL("triggered()"), self, SLOT("onCloseWindow()")) elif icon == "windowcloseall": connect(ACTION, SIGNAL("triggered()"), mdiArea, SLOT("closeAllSubWindows()")) elif icon == "windownext": ACTION.setShortcut(QKeySequence.NextChild) connect(ACTION, SIGNAL("triggered()"), mdiArea, SLOT("activateNextSubWindow()")) elif icon == "windowprevious": ACTION.setShortcut(QKeySequence.PreviousChild) connect(ACTION, SIGNAL("triggered()"), mdiArea, SLOT("activatePreviousSubWindow()")) elif icon == "help": connect(ACTION, SIGNAL("triggered()"), self, SLOT("help()")) elif icon == "changelog": connect(ACTION, SIGNAL("triggered()"), self, SLOT("changelog()")) elif icon == "tipoftheday": connect(ACTION, SIGNAL("triggered()"), self, SLOT("tipOfTheDay()")) elif icon == "about": connect(ACTION, SIGNAL("triggered()"), self, SLOT("about()")) elif icon == "whatsthis": connect(ACTION, SIGNAL("triggered()"), self, SLOT("whatsThisContextHelp()")) elif icon == "icon16": connect(ACTION, SIGNAL("triggered()"), self, SLOT("icon16()")) elif icon == "icon24": connect(ACTION, SIGNAL("triggered()"), self, SLOT("icon24()")) elif icon == "icon32": connect(ACTION, SIGNAL("triggered()"), self, SLOT("icon32()")) elif icon == "icon48": connect(ACTION, SIGNAL("triggered()"), self, SLOT("icon48()")) elif icon == "icon64": connect(ACTION, SIGNAL("triggered()"), self, SLOT("icon64()")) elif icon == "icon128": connect(ACTION, SIGNAL("triggered()"), self, SLOT("icon128()")) elif icon == "settingsdialog": connect(ACTION, SIGNAL("triggered()"), self, SLOT("settingsDialog()")) elif icon == "undo": connect(ACTION, SIGNAL("triggered()"), self, SLOT("undo()")) elif icon == "redo": connect(ACTION, SIGNAL("triggered()"), self, SLOT("redo()")) elif icon == "makelayercurrent": connect(ACTION, SIGNAL("triggered()"), self, SLOT("makeLayerActive()")) elif icon == "layers": connect(ACTION, SIGNAL("triggered()"), self, SLOT("layerManager()")) elif icon == "layerprevious": connect(ACTION, SIGNAL("triggered()"), self, SLOT("layerPrevious()")) elif icon == "textbold": ACTION.setCheckable(True) connect(ACTION, SIGNAL("toggled(bool)"), self, SLOT("setTextBold(bool)")) elif icon == "textitalic": ACTION.setCheckable(True) connect(ACTION, SIGNAL("toggled(bool)"), self, SLOT("setTextItalic(bool)")) elif icon == "textunderline": ACTION.setCheckable(True) connect(ACTION, SIGNAL("toggled(bool)"), self, SLOT("setTextUnderline(bool)")) elif icon == "textstrikeout": ACTION.setCheckable(True) connect(ACTION, SIGNAL("toggled(bool)"), self, SLOT("setTextStrikeOut(bool)")) elif icon == "textoverline": ACTION.setCheckable(True) connect(ACTION, SIGNAL("toggled(bool)"), self, SLOT("setTextOverline(bool)")) elif icon == "zoomrealtime": connect(ACTION, SIGNAL("triggered()"), self, SLOT("zoomRealtime()")) elif icon == "zoomprevious": connect(ACTION, SIGNAL("triggered()"), self, SLOT("zoomPrevious()")) elif icon == "zoomwindow": connect(ACTION, SIGNAL("triggered()"), self, SLOT("zoomWindow()")) elif icon == "zoomdynamic": connect(ACTION, SIGNAL("triggered()"), self, SLOT("zoomDynamic()")) elif icon == "zoomscale": connect(ACTION, SIGNAL("triggered()"), self, SLOT("zoomScale()")) elif icon == "zoomcenter": connect(ACTION, SIGNAL("triggered()"), self, SLOT("zoomCenter()")) elif icon == "zoomin": connect(ACTION, SIGNAL("triggered()"), self, SLOT("zoomIn()")) elif icon == "zoomout": connect(ACTION, SIGNAL("triggered()"), self, SLOT("zoomOut()")) elif icon == "zoomselected": connect(ACTION, SIGNAL("triggered()"), self, SLOT("zoomSelected()")) elif icon == "zoomall": connect(ACTION, SIGNAL("triggered()"), self, SLOT("zoomAll()")) elif icon == "zoomextents": connect(ACTION, SIGNAL("triggered()"), self, SLOT("zoomExtents()")) elif icon == "panrealtime": connect(ACTION, SIGNAL("triggered()"), self, SLOT("panrealtime()")) elif icon == "panpoint": connect(ACTION, SIGNAL("triggered()"), self, SLOT("panpoint()")) elif icon == "panleft": connect(ACTION, SIGNAL("triggered()"), self, SLOT("panLeft()")) elif icon == "panright": connect(ACTION, SIGNAL("triggered()"), self, SLOT("panRight()")) elif icon == "panup": connect(ACTION, SIGNAL("triggered()"), self, SLOT("panUp()")) elif icon == "pandown": connect(ACTION, SIGNAL("triggered()"), self, SLOT("panDown()")) elif icon == "day": connect(ACTION, SIGNAL("triggered()"), self, SLOT("dayVision()")) elif icon == "night": connect(ACTION, SIGNAL("triggered()"), self, SLOT("nightVision()")) elif scripted: ACTION.setIcon( QIcon(self.gAppDir + os.sep + "commands/" + icon + "/" + icon + ".png")) connect(ACTION, SIGNAL("triggered()"), self, SLOT("runCommand()")) else: ACTION.setEnabled(False) connect(ACTION, SIGNAL("triggered()"), self, SLOT("stub_implement()")) return ACTION
class MainWindow(QMainWindow): ''' MainWindow Class This is the main window for the pyDiveLog application. It contains the core GUI including the tool bar, menu bar, status bar, navigation tree, and individual model views. ''' def __init__(self): super(MainWindow, self).__init__() self._logbook = None self._logbookName = 'None' self._logbookPath = None self._createActions() self._createMenus() self._createLayout() self._createStatusBar() self.setWindowTitle(self.tr('pyDiveLog - %s') % self._logbookName) self._readSettings() def _createActions(self): 'Create main window actions' self._actNewLogbook = QAction(self.tr('&New Logbook...'), self) self._actNewLogbook.setShortcut(QKeySequence.New) self._actNewLogbook.setStatusTip(self.tr('Create a new Logbook file')) self._actNewLogbook.triggered.connect(self._actNewLogbookTriggered) self._actOpenLogbook = QAction(self.tr('&Open Logbook...'), self) self._actOpenLogbook.setShortcut(QKeySequence.Open) self._actOpenLogbook.setStatusTip(self.tr('Open an existing Logbook file')) self._actOpenLogbook.triggered.connect(self._actOpenLogbookTriggered) self._actCloseLogbook = QAction(self.tr('&Close Logbook'), self) self._actCloseLogbook.setStatusTip(self.tr('Close the current Logbook file')) self._actCloseLogbook.triggered.connect(self._actCloseLogbookTriggered) self._actExit = QAction(self.tr('E&xit'), self) self._actExit.setShortcut(QKeySequence.Quit) self._actExit.setStatusTip(self.tr('Exit the pyDiveLog application')) self._actExit.triggered.connect(self.close) def _createLayout(self): 'Create main window controls and layout' pass def _createMenus(self): 'Create main window menus' self._fileMenu = self.menuBar().addMenu(self.tr("&File")) self._fileMenu.addAction(self._actNewLogbook) self._fileMenu.addAction(self._actOpenLogbook) self._fileMenu.addAction(self._actCloseLogbook) self._fileMenu.addSeparator() self._fileMenu.addAction(self._actExit) def _createStatusBar(self): 'Initialize the main window status bar' self.statusBar().showMessage('Ready') def _closeLogbook(self): 'Close the current Logbook' if self._logbook is None: return self._logbook = None self._logbookName = 'None' self._logbookPath = None self._writeSettings() self.setWindowTitle(self.tr('pyDiveLog - %s') % self._logbookName) def _openLogbook(self, path): 'Open an existing Logbook' if self._logbook is not None: self._closeLogbook() if not os.path.exists(path): QMessageBox.warning(self, self.tr('Missing Logbook File'), self.tr('Unable to open Logbook "%s": file not found.') % os.path.basename(path), QMessageBox.Ok, QMessageBox.Ok) return #TODO: Handle a Schema Upgrade in a user-friendly manner self._logbook = Logbook(path, auto_update=False) self._logbookName = os.path.basename(path) self._logbookPath = path self._writeSettings() self.setWindowTitle(self.tr('pyDiveLog - %s') % self._logbookName) def _readSettings(self): 'Read main window settings from the configuration' settings = QSettings() settings.beginGroup('MainWindow') max = settings.value('max') size = settings.value('size') pos = settings.value('pos') file = settings.value('file') settings.endGroup() # Size and Position the Main Window if size is not None: self.resize(size) if pos is not None: self.move(pos) # HAX because QVariant is not exposed in PySide and the default # coercion to string is just stupid if max is not None and (max == 'true'): self.showMaximized() # Open the Logbook if file is not None: self._openLogbook(file) def _writeSettings(self): 'Write settings to the configuration' settings = QSettings() settings.beginGroup('MainWindow') settings.setValue('pos', self.pos()) settings.setValue('size', self.size()) settings.setValue('max', self.isMaximized()) settings.setValue('file', self._logbookPath) settings.endGroup() def closeEvent(self, e): 'Intercept an OnClose event' self._writeSettings() e.accept() #-------------------------------------------------------------------------- # Slots @QtCore.Slot() def _actCloseLogbookTriggered(self): 'Close Logbook Action Event Handler' self._closeLogbook() @QtCore.Slot() def _actNewLogbookTriggered(self): 'New Logbook Action Event Handler' if self._logbook is not None: dir = os.path.dirname(self._logbookPath) else: dir = os.path.expanduser('~') fn = QFileDialog.getSaveFileName(self, caption=self.tr('Save new Logbook as...'), dir=dir, filter='Logbook Files (*.lbk);;All Files (*.*)')[0] if fn == '': return if os.path.exists(fn): if QMessageBox.question(self, self.tr('Create new Logbook?'), self.tr('Logbook "%s" already exists. Would you like to overwrite it?') % os.path.basename(fn), QMessageBox.Yes | QMessageBox.No, QMessageBox.Yes) != QMessageBox.Yes: return # Try and remove the old Logbook file try: os.remove(fn) except: QMessageBox.error(self, self.tr('Cannot remove Logbook'), self.tr('Unable to remove Logbook file "%s". Please delete this file manually.') % os.path.basename(fn), QMessageBox.Ok, QMessageBox.Ok) return # Create a new Logbook File Logbook.Create(fn) self._openLogbook(fn) @QtCore.Slot() def _actOpenLogbookTriggered(self): 'Open Logbook Action Event Handler' if self._logbook is not None: dir = os.path.dirname(self._logbookPath) else: dir = os.path.expanduser('~') fn = QFileDialog.getOpenFileName(self, caption=self.tr('Select a Logbook file'), dir=dir, filter='Logbook Files (*.lbk);;All Files(*.*)')[0] if fn == '': return if not os.path.exists(fn): if QMessageBox.question(self, self.tr('Create new Logbook?'), self.tr('Logbook "%s" does not exist. Would you like to create it?') % os.path.basename(fn), QMessageBox.Yes | QMessageBox.No, QMessageBox.Yes) != QMessageBox.Yes: return Logbook.Create(fn) self._openLogbook(fn)
class AppWindow(QMainWindow): # ===================== # The Main Window Class # ===================== def __init__(self): # ==================== # Constructor Function # ==================== QMainWindow.__init__(self) self.setWindowTitle("Virtua Text Editor") self.setGeometry(300, 300, 1024, 768) QToolTip.setFont(QFont("Ubuntu", 10, QFont.Normal)) self.setToolTip('Application Window') # ================================ # Function to setup menus, etc etc # ================================ self.textEdit = QTextEdit() self.textEdit.setFont(QFont("Ubuntu", 12, QFont.Normal)) self.setCentralWidget(self.textEdit) self.create_menus() self.create_actions() self.fileMenu.addAction(self.newAction) self.fileMenu.addAction(self.openAction) self.fileMenu.addAction(self.saveAction) self.fileMenu.addAction(self.saveasAction) self.fileMenu.addSeparator() self.fileMenu.addAction(self.printAction) self.fileMenu.addSeparator() self.fileMenu.addAction(self.exitAction) self.editMenu.addAction(self.undoAction) self.editMenu.addAction(self.redoAction) self.editMenu.addAction(self.cutAction) self.editMenu.addAction(self.copyAction) self.editMenu.addAction(self.pasteAction) self.editMenu.addSeparator() self.editMenu.addAction(self.selectallAction) self.editMenu.addAction(self.deselectallAction) self.editMenu.addSeparator() self.editMenu.addAction(self.findAction) self.editMenu.addAction(self.findReplaceAction) self.helpMenu.addAction(self.aboutAction) self.app_status_bar = QStatusBar() self.app_status_bar.showMessage('Ready, v0.2', 10000) self.setStatusBar(self.app_status_bar) self.create_toolbar() self.toolbar.addAction(self.newAction) self.toolbar.addSeparator() self.toolbar.addAction(self.cutAction) self.toolbar.addAction(self.copyAction) self.toolbar.addAction(self.pasteAction) self.toolbar.addSeparator() self.toolbar.addAction(self.printAction) self.toolbar.addSeparator() self.toolbar.addAction(self.undoAction) self.toolbar.addAction(self.redoAction) self.toolbar.addSeparator() self.toolbar.addAction(self.findAction) self.toolbar.addAction(self.findReplaceAction) def create_toolbar(self): # =============================== # Function to create the toolbar. # =============================== self.toolbar = self.addToolBar('Main') self.toolbar.setToolButtonStyle(PySide.QtCore.Qt.ToolButtonTextUnderIcon) def newfile(self): self.textEdit.setText('') # TODO: Create the file/open method def openfile(self): print "Open File Menu Selected" # TODO: Create the file/save method def savefile(self): print "Save File Menu Selected" # TODO: Create the file/saveas method def saveasfile(self): print "Save As File Menu Selected" # TODO: Create the print method def print_page(self): print "Print Page Selected" # TODO: Create the find method def find_text(self): print "Find text option selected" # TODO: Create the replace method def find_replace_text(self): print "Replace text selected" def create_actions(self): # ========================================= # Function to create actions for menu items # ========================================= self.newAction = QAction(QIcon('digital_assets/document-new.svg'), 'New', self) self.newAction.setShortcut(QKeySequence.New) self.newAction.setStatusTip("Create a New File") self.newAction.setIconText("New") self.newAction.triggered.connect(self.newfile) self.openAction = QAction(QIcon('digital_assets/document-open.svg'), 'Open', self) self.openAction.setShortcut(QKeySequence.Open) self.openAction.setStatusTip("Open a file") self.openAction.triggered.connect(self.openfile) self.saveAction = QAction(QIcon('digital_assets/document-save.svg'), 'Save', self) self.saveAction.setShortcut(QKeySequence.Save) self.saveAction.setStatusTip("Save a file") self.saveAction.triggered.connect(self.savefile) self.saveasAction = QAction(QIcon('digital_assets/document-save-as.svg'), 'Save As', self) self.saveasAction.setShortcut(QKeySequence.SaveAs) self.saveasAction.setStatusTip("Save a File As....") self.saveasAction.triggered.connect(self.saveasfile) self.printAction = QAction(QIcon('digital_assets/document-print.svg'), 'Print', self) self.printAction.setShortcut(QKeySequence.Print) self.printAction.setStatusTip("Print") self.printAction.triggered.connect(self.print_page) self.exitAction = QAction(QIcon('digital_assets/application-exit.svg'), 'Exit', self) self.exitAction.setShortcut(QKeySequence.Quit) self.exitAction.setStatusTip("Exit the Application") self.exitAction.triggered.connect(self.quit_application) self.undoAction = QAction(QIcon('digital_assets/undo.svg'), 'Undo', self) self.undoAction.setShortcut(QKeySequence.Undo) self.undoAction.setStatusTip("Undo") self.undoAction.triggered.connect(self.textEdit.undo) self.redoAction = QAction(QIcon('digital_assets/redo.svg'), 'Redo', self) self.redoAction.setShortcut(QKeySequence.Redo) self.redoAction.setStatusTip("Redo") self.redoAction.triggered.connect(self.textEdit.redo) self.cutAction = QAction(QIcon('digital_assets/edit-cut.svg'), 'Cut', self) self.cutAction.setShortcut(QKeySequence.Cut) self.cutAction.setStatusTip("Cut") self.cutAction.setEnabled(False) self.cutAction.triggered.connect(self.textEdit.cut) self.copyAction = QAction(QIcon('digital_assets/edit-copy.svg'), 'Copy', self) self.copyAction.setShortcut(QKeySequence.Copy) self.copyAction.setStatusTip("Copy") self.copyAction.setEnabled(False) self.copyAction.triggered.connect(self.textEdit.copy) self.pasteAction = QAction(QIcon('digital_assets/edit-paste.svg'), 'Paste', self) self.pasteAction.setShortcut(QKeySequence.Paste) self.pasteAction.setStatusTip("Paste") self.pasteAction.setEnabled(False) self.pasteAction.triggered.connect(self.textEdit.paste) self.selectallAction = QAction(QIcon('digital_assets/edit-select-all.svg'), 'Select All', self) self.selectallAction.setShortcut(QKeySequence.SelectAll) self.selectallAction.setStatusTip("Select All") self.selectallAction.triggered.connect(self.textEdit.selectAll) self.deselectallAction = QAction(QIcon('digital_assets/edit-select-all.svg'), 'Deselect All', self) self.deselectallAction.setShortcut("Shift+Ctrl+A") self.deselectallAction.setStatusTip("Deselect All") self.deselectallAction.triggered.connect(self.deselect_all_text) self.findAction = QAction(QIcon('digital_assets/edit-find.svg'), 'Find', self) self.findAction.setShortcut(QKeySequence.Find) self.findAction.setStatusTip("Find") self.findAction.triggered.connect(self.find_text) self.findReplaceAction = QAction(QIcon('digital_assets/edit-find-replace.svg'), 'Replace', self) self.findReplaceAction.setShortcut(QKeySequence.Replace) self.findReplaceAction.setShortcut("Replace") self.findReplaceAction.triggered.connect(self.find_replace_text) self.aboutAction = QAction(QIcon('digital_assets/AppIcon.png'), 'About', self) self.aboutAction.setStatusTip("Displays info about the application") self.aboutAction.triggered.connect(self.show_about) def deselect_all_text(self): text_cursor = self.textEdit.textCursor() text_cursor.clearSelection() self.textEdit.setTextCursor(text_cursor) def create_menus(self): # ================================ # Function to create the menu bar. # ================================ self.fileMenu = self.menuBar().addMenu("File") self.fileMenu.setFont(QFont("Ubuntu", 10, QFont.Normal)) self.editMenu = self.menuBar().addMenu("Edit") self.editMenu.setFont(QFont("Ubuntu", 10, QFont.Normal)) self.helpMenu = self.menuBar().addMenu("Help") self.helpMenu.setFont(QFont("Ubuntu", 10, QFont.Normal)) def set_icon(self): # =============================== # Function to set the Window Icon # =============================== appicon = QIcon('digital_assets/AppIcon.png') self.setWindowIcon(appicon) def quit_application(self): # ================================ # Function to quit the application # ================================ userinfo = QMessageBox.question(self, "Confirmation", "This will quit, Do you want to continue?", QMessageBox.Yes | QMessageBox.No) if userinfo == QMessageBox.Yes: templateApp.quit() if userinfo == QMessageBox.No: pass def show_about(self): QMessageBox.about(self, "About Virtua Text Editor", "<b><h3>Virtua Text Editor</h3></b>" "<p><h4>Virtua Text Editor has been written to serve as a template" " that can be used as a basis for creating a working application." " All of the components that make up the core functions of an" " application, the main window, a status bar, menus and dialogs" " are provided here as a basis for writing something new and interesting</h4></p>") def center_application(self): # ============================================ # Function to center the Application on screen # ============================================ qrect = self.frameGeometry() centerpoint = QDesktopWidget().availableGeometry().center() qrect.moveCenter(centerpoint) self.move(qrect.topLeft())
def createAction(self, icon, toolTip, statusTip, scripted=False): """ TOWRITE :param `icon`: TOWRITE :type `icon`: QString :param `toolTip`: TOWRITE :type `toolTip`: QString :param `statusTip`: TOWRITE :type `statusTip`: QString :param `scripted`: TOWRITE :type `scripted`: bool :rtype: `QAction`_ .. TODO:: send the global Icon, Image, Commands Dirs in to be used. """ connect = self.connect # NOT local optimization, but for ease of the code looking similar to the C++ whash mdiArea = self.mdiArea # ditto ACTION = QAction( QIcon(self.gIconDir + os.sep + self.getSettingsGeneralIconTheme() + "/" + icon + ".png"), toolTip, self ) # QAction * # TODO: Qt4.7 wont load icons without an extension... ACTION.setStatusTip(statusTip) ACTION.setObjectName(icon) # TODO: Set What's This Context Help to statusTip for now so there is some infos there. # Make custom whats this context help popup with more descriptive help than just # the status bar/tip one liner(short but not real long) with a hyperlink in the custom popup # at the bottom to open full help file description. Ex: like wxPython AGW's SuperToolTip. ACTION.setWhatsThis(statusTip) # TODO: Finish All Commands ... <.< if icon == "donothing": connect(ACTION, SIGNAL("triggered()"), self, SLOT("doNothing()")) elif icon == "new": ACTION.setShortcut(QKeySequence.New) connect(ACTION, SIGNAL("triggered()"), self, SLOT("newFile()")) elif icon == "open": ACTION.setShortcut(QKeySequence.Open) connect(ACTION, SIGNAL("triggered()"), self, SLOT("openFile()")) elif icon == "save": ACTION.setShortcut(QKeySequence.Save) connect(ACTION, SIGNAL("triggered()"), self, SLOT("savefile()")) elif icon == "saveas": ACTION.setShortcut(QKeySequence.SaveAs) connect(ACTION, SIGNAL("triggered()"), self, SLOT("saveasfile()")) elif icon == "print": ACTION.setShortcut(QKeySequence.Print) connect(ACTION, SIGNAL("triggered()"), self, SLOT("print_()")) elif icon == "designdetails": ACTION.setShortcut(QKeySequence("Ctrl+D")) connect(ACTION, SIGNAL("triggered()"), self, SLOT("designDetails()")) elif icon == "exit": ACTION.setShortcut(QKeySequence("Ctrl+Q")) connect(ACTION, SIGNAL("triggered()"), self, SLOT("exit()")) elif icon == "cut": ACTION.setShortcut(QKeySequence.Cut) connect(ACTION, SIGNAL("triggered()"), self, SLOT("cut()")) elif icon == "copy": ACTION.setShortcut(QKeySequence.Copy) connect(ACTION, SIGNAL("triggered()"), self, SLOT("copy()")) elif icon == "paste": ACTION.setShortcut(QKeySequence.Paste) connect(ACTION, SIGNAL("triggered()"), self, SLOT("paste()")) elif icon == "windowcascade": connect(ACTION, SIGNAL("triggered()"), mdiArea, SLOT("cascade()")) elif icon == "windowtile": connect(ACTION, SIGNAL("triggered()"), mdiArea, SLOT("tile()")) elif icon == "windowclose": ACTION.setShortcut(QKeySequence.Close) connect(ACTION, SIGNAL("triggered()"), self, SLOT("onCloseWindow()")) elif icon == "windowcloseall": connect(ACTION, SIGNAL("triggered()"), mdiArea, SLOT("closeAllSubWindows()")) elif icon == "windownext": ACTION.setShortcut(QKeySequence.NextChild) connect(ACTION, SIGNAL("triggered()"), mdiArea, SLOT("activateNextSubWindow()")) elif icon == "windowprevious": ACTION.setShortcut(QKeySequence.PreviousChild) connect(ACTION, SIGNAL("triggered()"), mdiArea, SLOT("activatePreviousSubWindow()")) elif icon == "help": connect(ACTION, SIGNAL("triggered()"), self, SLOT("help()")) elif icon == "changelog": connect(ACTION, SIGNAL("triggered()"), self, SLOT("changelog()")) elif icon == "tipoftheday": connect(ACTION, SIGNAL("triggered()"), self, SLOT("tipOfTheDay()")) elif icon == "about": connect(ACTION, SIGNAL("triggered()"), self, SLOT("about()")) elif icon == "whatsthis": connect(ACTION, SIGNAL("triggered()"), self, SLOT("whatsThisContextHelp()")) elif icon == "icon16": connect(ACTION, SIGNAL("triggered()"), self, SLOT("icon16()")) elif icon == "icon24": connect(ACTION, SIGNAL("triggered()"), self, SLOT("icon24()")) elif icon == "icon32": connect(ACTION, SIGNAL("triggered()"), self, SLOT("icon32()")) elif icon == "icon48": connect(ACTION, SIGNAL("triggered()"), self, SLOT("icon48()")) elif icon == "icon64": connect(ACTION, SIGNAL("triggered()"), self, SLOT("icon64()")) elif icon == "icon128": connect(ACTION, SIGNAL("triggered()"), self, SLOT("icon128()")) elif icon == "settingsdialog": connect(ACTION, SIGNAL("triggered()"), self, SLOT("settingsDialog()")) elif icon == "undo": connect(ACTION, SIGNAL("triggered()"), self, SLOT("undo()")) elif icon == "redo": connect(ACTION, SIGNAL("triggered()"), self, SLOT("redo()")) elif icon == "makelayercurrent": connect(ACTION, SIGNAL("triggered()"), self, SLOT("makeLayerActive()")) elif icon == "layers": connect(ACTION, SIGNAL("triggered()"), self, SLOT("layerManager()")) elif icon == "layerprevious": connect(ACTION, SIGNAL("triggered()"), self, SLOT("layerPrevious()")) elif icon == "textbold": ACTION.setCheckable(True) connect(ACTION, SIGNAL("toggled(bool)"), self, SLOT("setTextBold(bool)")) elif icon == "textitalic": ACTION.setCheckable(True) connect(ACTION, SIGNAL("toggled(bool)"), self, SLOT("setTextItalic(bool)")) elif icon == "textunderline": ACTION.setCheckable(True) connect(ACTION, SIGNAL("toggled(bool)"), self, SLOT("setTextUnderline(bool)")) elif icon == "textstrikeout": ACTION.setCheckable(True) connect(ACTION, SIGNAL("toggled(bool)"), self, SLOT("setTextStrikeOut(bool)")) elif icon == "textoverline": ACTION.setCheckable(True) connect(ACTION, SIGNAL("toggled(bool)"), self, SLOT("setTextOverline(bool)")) elif icon == "zoomrealtime": connect(ACTION, SIGNAL("triggered()"), self, SLOT("zoomRealtime()")) elif icon == "zoomprevious": connect(ACTION, SIGNAL("triggered()"), self, SLOT("zoomPrevious()")) elif icon == "zoomwindow": connect(ACTION, SIGNAL("triggered()"), self, SLOT("zoomWindow()")) elif icon == "zoomdynamic": connect(ACTION, SIGNAL("triggered()"), self, SLOT("zoomDynamic()")) elif icon == "zoomscale": connect(ACTION, SIGNAL("triggered()"), self, SLOT("zoomScale()")) elif icon == "zoomcenter": connect(ACTION, SIGNAL("triggered()"), self, SLOT("zoomCenter()")) elif icon == "zoomin": connect(ACTION, SIGNAL("triggered()"), self, SLOT("zoomIn()")) elif icon == "zoomout": connect(ACTION, SIGNAL("triggered()"), self, SLOT("zoomOut()")) elif icon == "zoomselected": connect(ACTION, SIGNAL("triggered()"), self, SLOT("zoomSelected()")) elif icon == "zoomall": connect(ACTION, SIGNAL("triggered()"), self, SLOT("zoomAll()")) elif icon == "zoomextents": connect(ACTION, SIGNAL("triggered()"), self, SLOT("zoomExtents()")) elif icon == "panrealtime": connect(ACTION, SIGNAL("triggered()"), self, SLOT("panrealtime()")) elif icon == "panpoint": connect(ACTION, SIGNAL("triggered()"), self, SLOT("panpoint()")) elif icon == "panleft": connect(ACTION, SIGNAL("triggered()"), self, SLOT("panLeft()")) elif icon == "panright": connect(ACTION, SIGNAL("triggered()"), self, SLOT("panRight()")) elif icon == "panup": connect(ACTION, SIGNAL("triggered()"), self, SLOT("panUp()")) elif icon == "pandown": connect(ACTION, SIGNAL("triggered()"), self, SLOT("panDown()")) elif icon == "day": connect(ACTION, SIGNAL("triggered()"), self, SLOT("dayVision()")) elif icon == "night": connect(ACTION, SIGNAL("triggered()"), self, SLOT("nightVision()")) elif scripted: ACTION.setIcon(QIcon(self.gAppDir + os.sep + "commands/" + icon + "/" + icon + ".png")) connect(ACTION, SIGNAL("triggered()"), self, SLOT("runCommand()")) else: ACTION.setEnabled(False) connect(ACTION, SIGNAL("triggered()"), self, SLOT("stub_implement()")) return ACTION