def setup_menubar(self): menu_bar = QMenuBar() file_menu = menu_bar.addMenu("&File") file_menu.addAction(self.new_project_action) file_menu.addAction(self.show_settings_action) file_menu.addSeparator() file_menu.addAction(self.quit_action) view_menu = menu_bar.addMenu("&View") dockWidgets = self.findChildren(QDockWidget) for widget in dockWidgets: view_menu.addAction(widget.toggleViewAction()) debug_menu = menu_bar.addMenu("&Debug") debug_menu.addAction(self.start_listening_action) debug_menu.addAction(self.stop_listening_action) debug_menu.addSeparator() debug_menu.addAction(self.stop_debug_action) debug_menu.addAction(self.detach_debug_action) debug_menu.addSeparator() debug_menu.addAction(self.run_debug_action) debug_menu.addAction(self.step_over_action) debug_menu.addAction(self.step_into_action) debug_menu.addAction(self.step_out_action) self.setMenuBar(menu_bar)
def _createMenuBar(self): menuBar = QMenuBar(self) # File menu fileMenu = QMenu('&File', self) menuBar.addMenu(fileMenu) fileMenu.addAction(self.newAction) fileMenu.addAction(self.openAction) self.openRecentMenu = fileMenu.addMenu("Open Recent") fileMenu.addAction(self.saveAction) fileMenu.addSeparator() fileMenu.addAction(self.exitAction) # Edit menu editMenu = menuBar.addMenu("&Edit") editMenu.addAction(self.copyAction) editMenu.addAction(self.pasteAction) editMenu.addAction(self.cutAction) # .. Add submenu Find and Replace editMenu.addSeparator() findMenu = editMenu.addMenu("Find and Replace") findMenu.addAction(self.findAction) findMenu.addAction(self.replaceAction) # Help menu helpMenu = menuBar.addMenu(QIcon(":help-content.svg"), "&Help") helpMenu.addAction(self.helpContentAction) helpMenu.addAction(self.aboutAction) self.setMenuBar(menuBar)
def create_menu_bar(self): # Menu Bar menu_bar = QMenuBar() # File action_file = menu_bar.addMenu("&File") action_file.addAction("New", self.new_file, QKeySequence.New) action_file.addAction("Open", self.open_files, QKeySequence.Open) action_file.addAction("Save", self.save_file, QKeySequence.Save) action_file.addSeparator() action_file.addAction("Import", self.import_file) action_file.addAction("Export", self.export_file) action_file.addSeparator() action_file.addAction("Quit", self.quit, QKeySequence.Quit) # Edit action_edit = menu_bar.addMenu("&Edit") action_edit.addAction("Preferences", self.show_preferences) # View action_view = menu_bar.addMenu("&View") view_panels = action_view.addMenu("Panels") view_panels.addAction(self.editor.toggleViewAction()) view_panels.addAction(self.options.toggleViewAction()) view_panels.addAction(self.groups.toggleViewAction()) # Help action_help = menu_bar.addMenu("&Help") action_help.addAction("About", self.show_about) action_help.addAction("About Qt", QApplication.instance().aboutQt) return menu_bar
def createMenu(self): menuBar = QMenuBar() fileMenu = QMenu(self.tr("&File"), self) exitAction = fileMenu.addAction(self.tr("E&xit")) menuBar.addMenu(fileMenu) exitAction.triggered.connect(self.accept) return menuBar
class MainWindow(QMainWindow): def __init__(self, *args, **kwargs): super(MainWindow, self).__init__(*args, **kwargs) self.setWindowTitle("Map labelling tool") self.certral_widget = MainWidget() self.setCentralWidget(self.certral_widget) # Menubar elements exitAct = QAction(QIcon('exit.png'), '&Exit', self) exitAct.setShortcut('Ctrl+Q') exitAct.setStatusTip('Exit application') exitAct.triggered.connect(qApp.quit) openAct = QAction('Change image', self) openAct.triggered.connect(self.certral_widget.changeImage) saveAct = QAction('Save image', self) saveAct.triggered.connect(self.certral_widget.saveImage) paraStoreAct = QAction('Store params', self) paraStoreAct.triggered.connect(self.certral_widget.paraStore) paraReadAct = QAction('Read params', self) paraReadAct.triggered.connect(self.certral_widget.paraRead) self.menubar = QMenuBar(self) fileMenu = self.menubar.addMenu("File") fileMenu.addAction(openAct) fileMenu.addAction(saveAct) fileMenu.addAction(exitAct) paraMenu = self.menubar.addMenu("Param") paraMenu.addAction(paraStoreAct) paraMenu.addAction(paraReadAct)
def __init__(self): super().__init__() self.setWindowIcon(QIcon("gui/static/icon_logo.png")) self.setWindowTitle("T e b y g") self.move(300, 50) self.statusBar = QStatusBar() self.setStatusBar(self.statusBar) menu = QMenuBar() self.setMenuBar(menu) fileMenu = menu.addMenu("&File") fileMenu.addAction("Exit", self.close) settingsMenu = menu.addMenu("&Settings") settingsMenu.addAction("Database settings", self.show_database_settings) settingsMenu.addAction("Indexing settings", self.show_indexing_settings) settingsMenu.addAction("Matching settings", self.show_matching_settings) settingsMenu.addSeparator() settingsMenu.addAction("Other") self.window = Window(self.statusBar) self.setCentralWidget(self.window)
class Ui_Dialog(object): def setupUi(self, Dialog): def hello(self): print("hello") Dialog.setObjectName("Dialog") Dialog.setWindowModality(QtCore.Qt.ApplicationModal) Dialog.resize(1280, 840) exitAction = QAction(QIcon('exit.png'), 'Exit', parent=Dialog) exitAction.setShortcut('Ctrl+Q') exitAction.setStatusTip('Exit application') exitAction.triggered.connect(qApp.quit) SaveAction = QAction(QIcon('save.png'), 'Save', parent=Dialog) SaveAction.setShortcut('Ctrl+S') SaveAction.setStatusTip('Save') SaveAction.triggered.connect(hello) Anti_Action = QAction(QIcon('Anti.png'), 'Anti-Forensic Tool Execution Trace', parent=Dialog) Anti_Action.setStatusTip('Anti-Forensic Tool Execution Trace') Anti_Action.triggered.connect(hello) Mal_Action = QAction(QIcon('mal.png'), 'Malicious File Execution Trace', parent=Dialog) Mal_Action.setStatusTip('Malicious File Execution Trace') Mal_Action.triggered.connect(hello) Freq_Action = QAction(QIcon('freq.png'), 'Freqently Used File Trace', parent=Dialog) Freq_Action.setStatusTip('Freqently Used File Trace') Freq_Action.triggered.connect(hello) Cont_Action = QAction(QIcon('cont.png'), 'Continuous File Execution Trace', parent=Dialog) Cont_Action.setStatusTip('Continuous File Execution Trace') Cont_Action.triggered.connect(hello) Dele_Action = QAction(QIcon('dele.png'), 'Currently Deleted Executable Trace', parent=Dialog) Dele_Action.setStatusTip('Currently Deleted Executable Trace') Dele_Action.triggered.connect(Defile) self.menubar = QMenuBar(Dialog) self.menubar.setNativeMenuBar(False) self.filemenu = self.menubar.addMenu('&File') self.filemenu.addAction(exitAction) self.filemenu.addAction(SaveAction) self.toolmenu = self.menubar.addMenu('&Tool') self.toolmenu.addAction(Anti_Action) self.toolmenu.addAction(Freq_Action) self.toolmenu.addAction(Cont_Action) self.toolmenu.addAction(Dele_Action) self.toolmenu.addAction(Mal_Action)
def init_menubar(self): menubar = QMenuBar() # File menu file_menu = menubar.addMenu("&File") exit_action = QAction("&Exit", self) exit_action.setShortcut("Ctrl+Q") exit_action.setStatusTip("Exit application") exit_action.triggered.connect(qApp.quit) atomicswap_action = QAction("&New AtomicSwap", self) atomicswap_action.setShortcut("Ctrl+A") atomicswap_action.setStatusTip("Start new atomic swap contract") atomicswap_action.triggered.connect(self.atomicswap_window) file_menu.addAction(atomicswap_action) file_menu.addSeparator() file_menu.addAction(exit_action) # Help menu help_menu = menubar.addMenu("&Help") about_atomicswap_qt_action = QAction("About atomicswap-qt", self) about_atomicswap_qt_action.setStatusTip("About atomicswap-qt") about_atomicswap_qt_action.triggered.connect(self.about_dialog) about_qt_action = QAction("About Qt", self) about_qt_action.setStatusTip("About Qt") about_qt_action.triggered.connect(QApplication.aboutQt) help_menu.addAction(about_atomicswap_qt_action) help_menu.addAction(about_qt_action) self.setMenuBar(menubar)
def __create_menu_bar(self): """Creates the menu bar""" # create menus menu_bar = QMenuBar() # create file menu file_menu = QMenu('&File', menu_bar) close_action = file_menu.addAction('&Quit') close_action.triggered.connect(self.__close) close_action.setShortcut(QKeySequence.Quit) # edit menu edit_menu = QMenu('&Edit', menu_bar) config_dialog = ConfigDialog(self.__mainWindow) add_config_action = edit_menu.addAction('&Add configuration') add_config_action.triggered.connect(self.__add_configuration) resync_action = edit_menu.addAction('&Synchronize with server') resync_action.triggered.connect(self.__synchronize) preferences_action = edit_menu.addAction('&Preferences') preferences_action.triggered.connect(config_dialog.show) # create help menu help_menu = QMenu('&Help', menu_bar) about_qt_action = help_menu.addAction('About &Qt') about_qt_action.triggered.connect(self.__application.aboutQt) menu_bar.addMenu(file_menu) menu_bar.addMenu(edit_menu) menu_bar.addMenu(help_menu) return menu_bar
class MainWindow(QMainWindow): """The outer window to hold everything""" def __init__(self): """Set up the main window dimension etc""" super().__init__() self.resize(1024, 768) self.title = "Fibsem GUI" self.setWindowTitle(self.title) self.centre = MainWidget() self.setCentralWidget(self.centre) self.init_menu_bar() self.init_status_bar() def init_menu_bar(self): """Set up the menu bar""" self.menu = QMenuBar() self.menu.addMenu("Placeholder1") self.menu.addMenu("Placeholder2") self.menu.addMenu("Placeholder3") self.setMenuBar(self.menu) def init_status_bar(self): """Set up the status bar""" self.statusBar().showMessage('Ready')
def setup_menubar(self): menu_bar = QMenuBar() file_menu = menu_bar.addMenu("&File") file_menu.addAction(self.new_project_action) file_menu.addAction(self.show_settings_action) file_menu.addSeparator() file_menu.addAction(self.quit_action) view_menu = menu_bar.addMenu("&View") dockWidgets = self.findChildren(QDockWidget) for widget in dockWidgets: view_menu.addAction(widget.toggleViewAction()) debug_menu = menu_bar.addMenu("&Debug") debug_menu.addAction(self.start_listening_action) debug_menu.addAction(self.stop_listening_action) debug_menu.addSeparator() debug_menu.addAction(self.stop_debug_action) debug_menu.addAction(self.detach_debug_action) debug_menu.addSeparator() debug_menu.addAction(self.run_debug_action) debug_menu.addAction(self.step_over_action) debug_menu.addAction(self.step_into_action) debug_menu.addAction(self.step_out_action) search_menu = menu_bar.addMenu("&Search") search_menu.addAction(self.file_search_action) self.setMenuBar(menu_bar)
def _defineMenuBar(self) -> None: menuBar = QMenuBar(self) menuBar.setGeometry(QRect(0, 0, 240, 21)) # File menu fileMenu = QMenu("&File", self) fileMenu.addAction(self.actionAdd) fileMenu.addAction(self.actionRemove) fileMenu.addSeparator() fileMenu.addAction(self.actionRemoveAll) fileMenu.addSeparator() fileMenu.addAction(self.actionSave) # add File menu to menu bar menuBar.addMenu(fileMenu) # Settings menu settingsMenu = QMenu("&Settings", self) modeMenu = QMenu("&Mode", self) modeMenu.addAction(self.actionLightMode) modeMenu.addAction(self.actionDarkMode) settingsMenu.addMenu(modeMenu) # add Settings menu to menu bar menuBar.addMenu(settingsMenu) # set menu bar for window self.setMenuBar(menuBar)
def __build_menu(self): menu_bar = QMenuBar() file_menu = menu_bar.addMenu("File") self.__open_action = file_menu.addAction("Open...") self.__open_action.triggered.connect(self.__open_clicked) self.__recent_menu = file_menu.addMenu("Recent files") self.__save_action = file_menu.addAction("Save") self.__save_action.triggered.connect(self.__save_clicked) self.__save_as_action = file_menu.addAction("Save as...") self.__save_as_action.triggered.connect(self.__save_as_clicked) self.__close_action = file_menu.addAction("Close") self.__close_action.triggered.connect(self.__close_clicked) file_menu.addSeparator() self.__exit_action = file_menu.addAction("Exit") self.__exit_action.triggered.connect(self.__exit_clicked) sync_menu = menu_bar.addMenu("Sync") self.__import_action = sync_menu.addAction("Import...") self.__import_action.triggered.connect(self.__import_clicked) self.__export_action = sync_menu.addAction("Export...") self.__export_action.triggered.connect(self.__export_clicked) tab_menu = menu_bar.addMenu("Tab") self.__export_csv_action = tab_menu.addAction("Export CSV...") self.__export_csv_action.triggered.connect(self.__export_csv_clicked) self.__window.setMenuBar(menu_bar)
def initMainMenu(self): mainMenu = QMenuBar(self) self.setMenuBar(mainMenu) fileMenu = mainMenu.addMenu("&File") aboutMenu = mainMenu.addMenu("&About") aboutDialogAction = aboutMenu.addAction("Readme") aboutDialogAction.triggered.connect(self.showAboutDialog)
def __init__(self, app): QMainWindow.__init__(self, None) self.l.debug('Initializing MainWindow ...') self.setWindowTitle('MynPad') app.setWindowIcon(QIcon(':/icons/mynpad.png')) if os.name == 'nt': # On Windows, make sure to use a unique Application User Model Id, otherwise # Windows shows the default python icon in the taskbar # see http://stackoverflow.com/questions/1551605/how-to-set-applications-taskbar-icon-in-windows-7 myappid = 'afester.mynpad' import ctypes ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID( myappid) self.theApplication = app app.aboutToQuit.connect(self.saveState) # read the local configuration file iniPath = 'mynpad.ini' if not os.path.exists(iniPath): iniPath = os.path.join(expanduser("~"), iniPath) self.settings = Settings(iniPath) self.settings.load() # Set up the menu bar menuBar = QMenuBar(self) exitAction = QAction("Exit", self, triggered=self.theApplication.exit) fileMenu = menuBar.addMenu("&File") fileMenu.addAction(exitAction) aboutAction = QAction("About ...", self, triggered=self.handleAbout) helpMenu = menuBar.addMenu("&Help") helpMenu.addAction(aboutAction) self.setMenuBar(menuBar) # Setup the status bar self.statusBar = QStatusBar() self.statusBar.showMessage("Ready.") self.setStatusBar(self.statusBar) self.mainWidget = CentralWidget(self, self.settings) self.mainWidget.updateWindowTitle.connect(self.updateWindowTitle) self.setCentralWidget(self.mainWidget) # Reset main window size and position pos = self.settings.getMainWindowPos() self.move(pos.x(), pos.y()) size = self.settings.getMainWindowSize() self.resize(size) # initialize the browser tree (add the top nodes and expand the saved path) self.mainWidget.browserWidget.initialize()
def build_ui(self, window: QMainWindow): container = QWidget() box = QVBoxLayout() self.tab_list = QTabWidget() self.gfx = dict() self.scene = dict() self.gfx[Scan.SIDE_LEFT] = self.__create_tab(Scan.SIDE_LEFT, "left") self.gfx[Scan.SIDE_TOP] = self.__create_tab(Scan.SIDE_TOP, "top") self.gfx[Scan.SIDE_RIGHT] = self.__create_tab(Scan.SIDE_RIGHT, "right") for side in Scan.SIDES: self.scene[side] = Scene() self.scene[side].addRect(0, 0, 2054, 2054) self.gfx[side].setScene(self.scene[side]) box.addWidget(self.tab_list) container.setLayout(box) window.setCentralWidget(container) menu_bar = QMenuBar() file_menu: QMenu = menu_bar.addMenu("File") self.a_load: QAction = file_menu.addAction("Load Scans") file_menu.addSeparator() self.a_load_roi: QAction = file_menu.addAction("Load ROI") self.a_save_roi: QAction = file_menu.addAction("Save ROI") file_menu.addSeparator() a_exit: QAction = file_menu.addAction("Exit") a_exit.triggered.connect(window.close) edit_menu: QMenu = menu_bar.addMenu("Edit") self.a_add: QAction = edit_menu.addAction("Add point") window.setMenuBar(menu_bar) file_bar = QToolBar() self.slide_file = QSlider(orientation=Qt.Horizontal) self.slide_file.setRange(0, NUM_FILES - 1) self.slide_file.setSingleStep(1) self.slide_file.setPageStep(1) file_bar.addWidget(self.slide_file) self.slide_line = QSlider(orientation=Qt.Horizontal) self.slide_line.setRange(0, NUM_SCANS - 1) self.slide_line.setSingleStep(1) self.slide_line.setPageStep(16) file_bar.addWidget(self.slide_line) window.addToolBar(file_bar) window.setStatusBar(QStatusBar()) window.setWindowTitle("Ruler") window.resize(1200, 700)
class Window(QMainWindow): def __init__(self): super(Window, self).__init__() self.setWindowTitle("InformWindow") self.setGeometry(500, 450, 550, 400) self.text_edit = QtWidgets.QTextEdit(self) self.setCentralWidget(self.text_edit) self.createMenuBar() def createMenuBar(self): self.menuBar = QMenuBar(self) self.setMenuBar(self.menuBar) fileMenu = QMenu("&File", self) self.menuBar.addMenu(fileMenu) fileMenu.addAction("Open", self.action_clicked) fileMenu.addAction("Save", self.action_clicked) fileMenu = QMenu("&2File", self) self.menuBar.addMenu(fileMenu) fileMenu.addAction("Open", self.action_clicked) fileMenu.addAction("Save", self.action_clicked) @QtCore.pyqtSlot() def action_clicked(self): action = self.sender() if action.text() == "Open": fname = QFileDialog.getOpenFileName(self)[0] try: f = open(fname, 'r') with f: data = f.read() self.text_edit.setText(data) f.close() except FileNotFoundError: print("No such file") elif action.text() == "Save": fname = QFileDialog.getSaveFileName(self)[0] try: f = open(fname, 'w') text = self.text_edit.toPlainText() f.write(text) f.close() except FileNotFoundError: print("No such file")
def __init__(self, app): QMainWindow.__init__(self, None) self.l.debug('Initializing MainWindow ...') self.setWindowTitle('MynPad') app.setWindowIcon(QIcon(':/icons/mynpad.png')) if os.name == 'nt': # On Windows, make sure to use a unique Application User Model Id, otherwise # Windows shows the default python icon in the taskbar # see http://stackoverflow.com/questions/1551605/how-to-set-applications-taskbar-icon-in-windows-7 myappid = 'afester.mynpad' import ctypes; ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID(myappid) self.theApplication = app app.aboutToQuit.connect(self.saveState) # read the local configuration file iniPath = 'mynpad.ini' if not os.path.exists(iniPath): iniPath = os.path.join(expanduser("~"), iniPath) self.settings = Settings(iniPath) self.settings.load() # Set up the menu bar menuBar = QMenuBar(self) exitAction = QAction("Exit", self, triggered=self.theApplication.exit) fileMenu = menuBar.addMenu("&File") fileMenu.addAction(exitAction) aboutAction = QAction("About ...", self, triggered = self.handleAbout) helpMenu = menuBar.addMenu("&Help") helpMenu.addAction(aboutAction) self.setMenuBar(menuBar) # Setup the status bar self.statusBar = QStatusBar() self.statusBar.showMessage("Ready.") self.setStatusBar(self.statusBar) self.mainWidget = CentralWidget(self, self.settings) self.mainWidget.updateWindowTitle.connect(self.updateWindowTitle) self.setCentralWidget(self.mainWidget) # Reset main window size and position pos = self.settings.getMainWindowPos() self.move(pos.x(), pos.y()) size = self.settings.getMainWindowSize() self.resize(size) # initialize the browser tree (add the top nodes and expand the saved path) self.mainWidget.browserWidget.initialize()
class HomePage(QDialog): def __init__(self, parent=None): super(HomePage, self).__init__(parent) # Resize the page self.resize(1200, 800) self.setWindowTitle("Outil de statistiques pour le Golf") self.setupUi() def setupUi(self): # Create QMenuBar self.header = QMenuBar() self.menu_carte = self.header.addMenu("Carte de score") self.menu_carte.addAction("Enregistrer une cartes", self.addNewCard) self.menu_carte.addAction("Mes cartes", self.scoreCards) self.menu_stats = self.header.addMenu("Statistiques") self.menu_stats.addAction("Ouvrir mes statistiques", self.toDefine) # Create layout self.layout = QGridLayout() # Form structuration self.btn_cards = QPushButton('Mes cartes') self.btn_stats = QPushButton('Mes Stats') self.btn_cards.setMinimumHeight(200) self.btn_stats.setMinimumHeight(200) self.btn_cards.clicked.connect(self.scoreCards) self.btn_stats.clicked.connect(self.toDefine) # Add widgets self.layout.addWidget(self.btn_stats, 0, 1) self.layout.addWidget(self.btn_cards, 0, 2) self.setLayout(self.layout) def scoreCards(self): dialog = scorecard.ScoreCard() dialog.show() dialog.exec_() def toDefine(self): print("Coming soon") def addNewCard(self): dialog = cardnew.cardDetail() dialog.show() dialog.exec_()
class Window(QMainWindow): def __init__(self): super(Window, self).__init__() self.setWindowTitle('Redactor') self.setGeometry(300,250,350,200) self.text_edit = QtWidgets.QTextEdit(self) self.setCentralWidget(self.text_edit) self.createMunuBar() def createMunuBar(self): self.menuBar = QMenuBar(self) self.setMenuBar(self.menuBar) fileMenu = QMenu("&Файл", self) self.menuBar.addMenu(fileMenu) fileMenu.addAction("Открыть", self.action_cliced) fileMenu.addAction("Cосхранить", self.action_cliced) @QtCore.pyqtSlot() def action_cliced(self): action = self.sender() if action.text() == "Открыть": fname = QFileDialog.getOpenFileName(self)[0] try: f = open(fname, 'r') with f: data = f.read() self.text_edit.setText(data) except FileNotFoundError: print("No such file") elif action.text() == "Cосхранить": fname = QFileDialog.getSaveFileName(self)[0] try: f = open(fname, 'w') text = self.text_edit.toPlainText() f.write(text) f.close() except FileNotFoundError: print("No such file")
def createMenuBar(self, menubar: QMenuBar): menubar.addSeparator() for config in menubar_configs: for label, items in config.items(): menu = menubar.addMenu(label) for item in items: text = item.get('text') sc = item.get('shortcut', None) icon = item.get('icon', None) sub = item.get('sub', None) if sub: submenu = QMenu(text, self) for each_sub in sub: text = each_sub.get('text') action = QAction(text, self) action.triggered.connect( getattr(self, each_sub.get('action'))) submenu.addAction(action) menu.addMenu(submenu) continue action = QAction(text, self) if sc: action.setShortcut(sc) if icon: action.setIcon(qta.icon(icon)) action.triggered.connect( getattr(self, item.get('action')) # self.actions.get() ) menu.addAction(action) self.more_actions()
def initUI(self): self.setGeometry(300, 300, 416, 234) self.setWindowTitle('reader') self.setWindowFlag(Qt.WindowStaysOnTopHint) self.setWindowOpacity(1) #设置透明度 self.grid = QGridLayout() #设置布局 opacityAction1 = QAction('&25%', self) opacityAction1.triggered.connect(partial(self.opacity, 0.25)) opacityAction2 = QAction('&50%', self) opacityAction2.triggered.connect(partial(self.opacity, 0.5)) opacityAction3 = QAction('&75%', self) opacityAction3.triggered.connect(partial(self.opacity, 0.75)) opacityAction4 = QAction('&100%', self) opacityAction4.triggered.connect(partial(self.opacity, 1)) menubar = QMenuBar() #创建菜单 self.setopacity = menubar.addMenu('&opacity') #设置透明度 self.setopacity.addAction(opacityAction1) self.setopacity.addAction(opacityAction2) self.setopacity.addAction(opacityAction3) self.setopacity.addAction(opacityAction4) self.textpart = QTextBrowser() self.grid.addWidget(menubar) self.grid.addWidget(self.textpart) self.setLayout(self.grid) self.show() self.init_action()
def __init__(self, parent=None): super(ConfigDialog, self).__init__(parent) self.contentsWidget = QListWidget() self.contentsWidget.setViewMode(QListView.IconMode) self.contentsWidget.setIconSize(QSize(96, 84)) self.contentsWidget.setMovement(QListView.Static) self.contentsWidget.setMaximumWidth(128) self.contentsWidget.setSpacing(12) self.createIcons() closeButton = QPushButton("Close") closeButton.clicked.connect(self.close) # horizontalLayout = QHBoxLayout() # horizontalLayout.addWidget(self.contentsWidget) # horizontalLayout.addWidget(self.pagesWidget, 1) buttonsLayout = QHBoxLayout() buttonsLayout.addStretch(1) buttonsLayout.addWidget(closeButton) mainLayout = QVBoxLayout() mainLayout.addWidget(self.contentsWidget, Qt.AlignCenter) mainLayout.addStretch(1) mainLayout.addSpacing(12) mainLayout.addLayout(buttonsLayout) self.setLayout(mainLayout) self.setWindowTitle("Config Dialog") menuBar = QMenuBar(self) # group.setExclusive(True) ## 只允许一个 menu = menuBar.addMenu("&About") menu.addAction('about', lambda: QApplication.instance().aboutQt()) mainLayout.setMenuBar(menuBar)
def initUI(self): exitAct = QAction(QIcon('exit.png'), '&Exit', self) exitAct.triggered.connect(qApp.quit) openInput = QAction('&Open Input', self) img1 = openInput.triggered.connect(self.open_input) openTarget = QAction('&Open Target', self) img2 = openTarget.triggered.connect(self.open_target) menubar = QMenuBar(self) fileMenu = menubar.addMenu('&File') fileMenu.addAction(openInput) fileMenu.addAction(openTarget) fileMenu.addAction(exitAct) self.setWindowTitle(self.title) self.setContentsMargins(0, 39, 0, 0) self.setWindowState(QtCore.Qt.WindowMaximized) button = QPushButton('Create triangulation', self) button2 = QPushButton('Morph', self) button.move(0, 20) button2.move(104, 20) screenShape = QDesktopWidget().screenGeometry() width = screenShape.width() button.resize(104, 25) button2.resize(50, 25) button.setStyleSheet("Text-align:center") button2.setStyleSheet("Text-align:center") button.clicked.connect(self.triangulation) button2.clicked.connect(self.morph) self.show()
def initHelp(self): Bar_help = QMenuBar(self) fileMenu = QMenu('Help', self) im = QAction('Shortcuts', self) im.triggered.connect(show_help_shortcuts) fileMenu.addAction(im) im = QAction('Help', self) im.triggered.connect(self.help_browser) fileMenu.addAction(im) im = QAction('Buy', self) im.triggered.connect(self.help_buy) fileMenu.addAction(im) Bar_help.addMenu(fileMenu) self.menubar.setCornerWidget(Bar_help)
def __init__(self, settings, *args, **kwargs): super().__init__(*args, **kwargs) layout = QGridLayout(self) #layout.setContentsMargins(0, 0, 0, 0) settings_tabs = QTabWidget() layout.addWidget(settings_tabs) form = 'Gaussian' self.method = MethodOption(settings, form) settings_tabs.addTab(self.method, "Method") self.basis = BasisWidget(settings, form) settings_tabs.addTab(self.basis, "Basis Sets") #menu stuff menu = QMenuBar() self.presets_menu = menu.addMenu("Presets") menu.setNativeMenuBar(False) self._menu = menu layout.setMenuBar(menu) self.settings = settings self.presets = {} self.presets['Gaussian'] = loads(self.settings.gaussian_presets) self.presets['ORCA'] = loads(self.settings.orca_presets) self.presets['Psi4'] = loads(self.settings.psi4_presets) self.refresh_presets()
class QtMenuBar(MenuBar): def __init__(self): super().__init__() self.__qMenuBar = QMenuBar() def getQMenuBar(self) -> QMenuBar: return self.__qMenuBar def _makeMenu(self, title: str) -> Menu: return QtMenu(title) def _addMenuToView(self, menu: Menu) -> None: self.__qMenuBar.addMenu(menu.getQMenu()) def _removeMenuFromView(self, menu) -> None: pass
def initUi(self): self.setGeometry(400, 400, 600, 450) self.setWindowTitle('Большая задача по Maps API') self.setFixedSize(self.size()) self.map = QLabel("", self) self.map.setGeometry(0, 0, 600, 450) self.map.setPixmap(self.get_map()) self.adressPt = QLabel("Россия, Москва", self) self.adressPt.setGeometry(50, 0, 300, 20) self.adressPt.setVisible(True) mainMenu = QMenuBar(self) setupMenu = mainMenu.addMenu('Setup') showbtn = QAction('Искать', self) showbtn.setShortcut('Ctrl+S') showbtn.triggered.connect(self.SHOw) mapTypeBtn = QAction("Сменить слой", self) mapTypeBtn.setShortcut('Ctrl+M') mapTypeBtn.triggered.connect(self.change_map_type) mapPtBtn = QAction("Сброс поискового результата", self) mapPtBtn.setShortcut('Ctrl+R') mapPtBtn.triggered.connect(self.clearPt) setupMenu.addAction(showbtn) setupMenu.addAction(mapTypeBtn) setupMenu.addAction(mapPtBtn)
def createMenu(self): menubar = QMenuBar(self) fileMenu = menubar.addMenu('File') editMenu = menubar.addMenu('Edit') loadSequence = QAction('Open', self) loadSequence.triggered.connect(self.loadFile) loadSequence.setShortcut('Ctrl+O') saveSequence = QAction('Save', self) saveSequence.triggered.connect(self.saveFile) saveSequence.setShortcut('Ctrl+S') addSequence = QAction('Add Sequence', self) addSequence.triggered.connect(self.addSequence) selectAll = QAction('Select All', self) selectAll.triggered.connect(self.selectAll) selectAll.setShortcut('Ctrl+A') clearDone = QAction('Clear Done', self) clearDone.triggered.connect(self.clearDone) fileMenu.addAction(loadSequence) fileMenu.addAction(saveSequence) editMenu.addAction(addSequence) editMenu.addAction(selectAll) editMenu.addAction(clearDone) return menubar
def initUI(self): exitAct = QAction(QIcon('exit.png'), '&Exit', self) exitAct.triggered.connect(qApp.quit) openInput = QAction('&Open Input', self) img1 = openInput.triggered.connect(self.open_image) openTarget = QAction('&Open Target', self) img2 = openTarget.triggered.connect(self.open_image) menubar = QMenuBar(self) fileMenu = menubar.addMenu('&File') fileMenu.addAction(openInput) fileMenu.addAction(openTarget) fileMenu.addAction(exitAct) self.setWindowTitle(self.title) self.setContentsMargins(0, 35, 0, 0) self.setWindowState(QtCore.Qt.WindowMaximized) button = QPushButton('Equalize Histogram', self) button.move(0, 20) screenShape = QDesktopWidget().screenGeometry() width = screenShape.width() button.resize(width, 25) button.setStyleSheet("Text-align:left") button.clicked.connect(self.equal_hist) self.show()
def _setup_(self): menu_bar = QMenuBar() file_menu = menu_bar.addMenu('File') open_action = file_menu.addAction('Open') open_action.triggered.connect(self.data_context.open) save_action = file_menu.addAction('Save') save_action.triggered.connect(self.data_context.save) save_as_action = file_menu.addAction('Save As') save_as_action.triggered.connect(self.data_context.save_as) load_from_matplot_action = menu_bar.addAction('Import from Matplotlib') load_from_matplot_action.triggered.connect(self._import_matplotlib_colormap_) self._layout.addWidget(menu_bar, 0, 0, 1, 2, Qt.AlignLeft) self._plot = PlotMasterWidget() self.bindings.set_binding('title', self._plot, 'set_title') self._red_plot = self._plot.plot(0, 0, 'r', name='red', allow_remove=False) self._green_plot = self._plot.plot(0, 0, 'g', name='green', allow_remove=False) self._blue_plot = self._plot.plot(0, 0, 'b', name='blue', allow_remove=False) self._plot.set_xlabel('value') self._plot.set_ylabel('color value') self._layout.addWidget(self._plot, 1, 1) tool_box = QGroupBox('Tools') tool_box_layout = QGridLayout() tool_box_layout.setAlignment(Qt.AlignLeft | Qt.AlignTop) tool_box.setLayout(tool_box_layout) self._layout.addWidget(tool_box, 1, 0) self._add_range_slider_('colors', tool_box_layout, 0) self._add_range_slider_('red', tool_box_layout, 1) self._add_range_slider_('green', tool_box_layout, 2) self._add_range_slider_('blue', tool_box_layout, 3) image_display = self.add_widget(ImageRenderWidget(keep_aspect_ratio=False), 'color_image', 'set_image', height=50) self._layout.addWidget(image_display, 2, 0, 1, 2, Qt.AlignJustify)
def menubar(): """Return a newly created parent-less menu bar that's used when there is no main window.""" m = QMenuBar() m.addMenu(menu_file(m)) m.addMenu(menu_edit(m)) m.addMenu(menu_window(m)) m.addMenu(menu_sessions(m)) m.addMenu(menu_help(m)) return m
def initUI(self): QToolTip.setFont(QFont('SansSerif', 10)) self.setToolTip('This is a <b>QWidget</b> widget.') #quitBtn = QPushButton('Quit', self) #quitBtn.clicked.connect(self.quitBtnEvent()) #quitBtn.clicked.connect(QCoreApplication.instance().quit) #quitBtn.setToolTip('This is a <b>QPushButton</b> widget.') #quitBtn.resize(quitBtn.sizeHint()) exitAction = QAction(QIcon('application-exit-4.png'), '&Exit', self) exitAction.setShortcut('Alt+F4') exitAction.setStatusTip('Exit Application') exitAction.triggered.connect(qApp.quit) menuBar = QMenuBar() fileMenu = menuBar.addMenu('&File') fileMenu.addAction(exitAction) fileMenu.resize(fileMenu.sizeHint()) toolBar = QToolBar(self) toolBar.addAction(exitAction) #toolBar.resize(toolBar.sizeHint()) toolBar.setFixedHeight(60) hozLine = QFrame() hozLine.setFrameStyle(QFrame.HLine) #hozLine.setSizePolicy(QSizePolicy.Minimum,QSizePolicy.Expanding) statusBar = QStatusBar(self) statusBar.showMessage('Ready') grid = QGridLayout() lbl_1 = QLabel('1,1') lbl_2 = QLabel('1,2') lbl_3 = QLabel('2,1') lbl_4 = QLabel('2,2') grid.addWidget(lbl_1, 1, 1) grid.addWidget(lbl_2, 1, 2) grid.addWidget(lbl_3, 2, 1) grid.addWidget(lbl_4, 2, 2) vbox = QVBoxLayout() vbox.addWidget(menuBar) vbox.addWidget(hozLine) vbox.addWidget(toolBar) # vbox.addWidget(hozLine) vbox.addLayout(grid) vbox.addStretch(1) vbox.addWidget(statusBar) self.setLayout(vbox) self.setGeometry(300, 300, 500, 500) self.setWindowTitle('Photos') self.setWindowIcon(QIcon('camera-photo-5.png')) self.center() self.show()
def setupUI(self): menu_bar = QMenuBar() file = menu_bar.addMenu("&File") help = menu_bar.addMenu("&Help") build = menu_bar.addMenu("&Build") exit = menu_bar.addMenu("&Exit") tabs = QTabWidget() centerwidget = QWidget() vshadertab = QWidget() fshadertab = QWidget() vshadertab_layout = QVBoxLayout(vshadertab) fshadertab_layout = QVBoxLayout(fshadertab) fshadereditor = GLSLEditor() vshadereditor = GLSLEditor() fshadertab_layout.addWidget(fshadereditor) vshadertab_layout.addWidget(vshadereditor) tabs.addTab(vshadertab, "Vertex Shader") tabs.addTab(fshadertab, "Fragment Shader") vbox = QVBoxLayout() vbox.addWidget(menu_bar) vbox.addWidget(tabs) centerwidget.setLayout(vbox) self.setCentralWidget(centerwidget) pass
class SubtleMainWindow(QMainWindow): def __init__(self, paths=[]): QMainWindow.__init__( self ) self.setWindowTitle( 'Subtle' ) self.setAcceptDrops( True ) self._menu = QMenuBar( self ) fileMenu = self._menu.addMenu( '&File' ) fileMenu.addAction( QAction('&Open', fileMenu) ) close = QAction('&Quit', fileMenu) close.setShortcut( QKeySequence(QKeySequence.Quit) ) close.triggered.connect( self._close_action ) fileMenu.addAction( close ) self.setMenuBar( self._menu ) self._tree = SubtleTreeWidget(self, paths_to_items_list(self, paths)) self.setCentralWidget( self._tree ) @QtCore.pyqtSlot() def _close_action(self): self.close() def dragEnterEvent(self, event): event.acceptProposedAction() def dropEvent(self, event): items = paths_to_items_list(self._tree, event.mimeData().urls()) self._tree.addTopLevelItems( items ) self.update() event.acceptProposedAction() def update(self): items = [ self._tree.itemAt(i, 0) for i in range(0, self._tree.topLevelItemCount()) ] for item in items: print( 'item {}'.format(item.data(0, SubtleTreeWidget.ITEM_ROLE)) )
class DragWidget(QWidget): spacerX = 16 spacerY = 16 clipicon = None windowclass_signal = pyqtSignal(str) query = pyqtSignal() def __init__(self, path, parent=None): super(DragWidget, self).__init__(parent) self.setMinimumSize(400, 200) self.setAcceptDrops(True) self.menubar = QMenuBar() fileMenu = self.menubar.addMenu('File') editMenu = self.menubar.addMenu('Edit') exitAction = QAction('Open', self) prefAction = QAction('Pref', self) fileMenu.addAction(exitAction) editMenu.addAction(prefAction) self.path = path self.icons = [] # self.clipicon = None for name in os.listdir(path): icon_widget = IconWidget(self, name=name, path=self.path) icon_widget.new_window.connect(self.windowclass_signal.emit) icon_widget.clipboard.connect(self.on_clipboard) self.icons.append(icon_widget) # self.icons[-1].move(DragWidget.spacerX, DragWidget.spacerY) self.icons[-1].setAttribute(Qt.WA_DeleteOnClose) self.clean_up() # self.updateScrollArea() def updateScrollArea(self): """ set the dimension of the widget """ iconx = [] icony = [] for item in self.icons: iconx.append(item.x()) icony.append(item.y()) self.setMinimumWidth(max(iconx)+75) self.setMinimumHeight(max(icony)+75) def dragEnterEvent(self, event): event.accept() def dragMoveEvent(self, event): event.accept() def dropEvent(self, event): event.accept() if event.mimeData().hasFormat("application/x-icon"): name = event.source().name icon_widget = IconWidget(self, name=name, path=self.path) icon_widget.new_window.connect(self.windowclass_signal.emit) self.icons.append(icon_widget) self.icons[-1].move(event.pos().x(), event.pos().y()) self.icons[-1].show() self.updateScrollArea() def mousePressEvent(self, event): if event.buttons() == Qt.LeftButton: for item in self.icons: item.reset_selection() if event.buttons() == Qt.RightButton: menu = QMenu("Window Menu") clean = menu.addAction("Clean Up") clean.triggered.connect(self.clean_up) if DragWidget.clipicon is not None: paste = menu.addAction("Paste") paste.triggered.connect(self.paste_icon) eventpos = event.screenPos() qpoint = QPoint(eventpos.x(), eventpos.y()) menu.exec_(qpoint) def mouseDoubleClickEvent(self, event): print("Double Click") self.query.emit() def clean_up(self): print("clean_up method") # print("sw=", self.window().width()) for item in self.icons: item.move(DragWidget.spacerX, DragWidget.spacerY) # initial icon placement DragWidget.spacerX += 100 if DragWidget.spacerX + 100 > self.window().width(): DragWidget.spacerY += 75 DragWidget.spacerX = 16 # reset placement values DragWidget.spacerX = 16 DragWidget.spacerY = 16 self.updateScrollArea() def paste_icon(self): print("---") print("srce=", self.clipicon.path + "/" + self.clipicon.name) # print("res=", self.clipicon.path + "/" + self.clipicon.name) print("dest=", self.path + "/") # if os.path.isdir(os.path.join(self.clipicon.path, self.clipicon.name)): SRCE = self.clipicon.path + "/" + self.clipicon.name DEST = self.path+"/" + self.clipicon.name shutil.copytree(SRCE, DEST) def on_clipboard(self, icon): print("realpath", self.path) print("clip_icon_name=", icon.name) DragWidget.clipicon = icon
class MainWindow(QMainWindow): def __init__(self): super(MainWindow, self).__init__() self.parts = [] self.blocks = [] self.centralBlock = [0, 0, 0, 1] self.resolution = 16 self.createGUI() self.createMenu() self.connectSlots() self.project_file = "" self.current_block = 0 self.block_count = 0 def createGUI(self): self.widget = QWidget(self) self.gvMain = MainView(self, 0, self.blocks) self.views = {key: XYZview(self, self.blocks, key) for key in ('xy', 'yz', 'zx')} self.cbSelectBox = QComboBox(self) self.pbAddBox = QPushButton("Add Box", self) self.pbDeleteBox = QPushButton("Delete selected box", self) self.slScale = QSlider(self) self.slScale.setOrientation(Qt.Horizontal) self.slScale.setRange(2, 15) self.slScale.setValue(5) self.slResolution = QSlider(self) self.slResolution.setOrientation(Qt.Horizontal) self.slResolution.setRange(1, 6) # resolution is 2**this_value self.slResolution.setValue(4) # 2**4 is 16 -- initial resolution self.turn_buttons = {'x': QPushButton("Turn around X axis", self), 'y': QPushButton("Turn around Y axis", self), 'z': QPushButton("Turn around Z axis", self)} self.swap_buttons = {'xy': QPushButton("Swap X and Y", self), 'yz': QPushButton("Swap Y and Z", self), 'zx': QPushButton("Swap Z and X", self)} self.grLayout = QGridLayout() self.grLayout.addWidget(QLabel("Main view"), 0, 0) self.grLayout.addWidget(self.gvMain, 1, 0) self.grLayout.addWidget(QLabel("Y view"), 0, 1) self.grLayout.addWidget(self.views['zx'], 1, 1) self.vbRightLayout = QVBoxLayout() self.vbRightLayout.addWidget(QLabel("Select box")) self.vbRightLayout.addWidget(self.cbSelectBox) self.vbRightLayout.addWidget(self.pbAddBox) self.vbRightLayout.addWidget(self.pbDeleteBox) self.vbRightLayout.addWidget(QLabel("Scale")) self.vbRightLayout.addWidget(self.slScale) self.vbRightLayout.addWidget(QLabel("Resolution")) self.vbRightLayout.addWidget(self.slResolution) self.vbRightLayout.addItem( QSpacerItem(0, 0, QSizePolicy.Minimum, QSizePolicy.Expanding)) for button in self.swap_buttons.values(): self.vbRightLayout.addWidget(button) for button in self.turn_buttons.values(): self.vbRightLayout.addWidget(button) self.hbMainLayout = QHBoxLayout() self.hbMainLayout.addLayout(self.grLayout, 10) self.hbMainLayout.addLayout(self.vbRightLayout, 1) self.grLayout.addWidget(QLabel("X view"), 2, 0) self.grLayout.addWidget(self.views['yz'], 3, 0) self.grLayout.addWidget(QLabel("Z view"), 2, 1) self.grLayout.addWidget(self.views['xy'], 3, 1) self.widget.setLayout(self.hbMainLayout) self.setCentralWidget(self.widget) self.setWindowTitle("Nodebox editor") self.resize(1000, 600) def createMenu(self): self.menuBar = QMenuBar() self.fileMenu = self.menuBar.addMenu("&File") self.helpMenu = self.menuBar.addMenu("&Help") self.aNewProject = self.fileMenu.addAction("Start new project") self.aOpen = self.fileMenu.addAction("Open") self.aSave = self.fileMenu.addAction("Save as...") self.aExport = self.fileMenu.addAction("Export as...") self.fileMenu.addSeparator() self.aExitApp = self.fileMenu.addAction("Exit") self.setMenuBar(self.menuBar) def addBox(self): self.blocks.append(Block([-8, -8, -8, 1], [8, 8, 8, 1])) self.block_count += 1 # BTW, we will not decrease this value self.cbSelectBox.addItems(["Block" + str(self.block_count)]) self.cbSelectBox.setCurrentIndex(self.cbSelectBox.count()-1) self.update() self.current_block = self.blocks[self.cbSelectBox.currentIndex()] self.sendCurrentBlock(self.current_block) def deleteBox(self): if self.cbSelectBox.count() != 0: idx = self.cbSelectBox.currentIndex() del self.blocks[idx] self.cbSelectBox.removeItem(idx) if self.cbSelectBox.count() != 0: self.cbSelectBox.setCurrentIndex(0) self.current_block = self.blocks[0] self.sendCurrentBlock(self.current_block) else: self.current_block = 0; self.sendCurrentBlock(0) self.update() def connectSlots(self): self.aExitApp.triggered.connect(lambda: sys.exit(0)) self.aExport.triggered.connect(self.actionExport) self.aSave.triggered.connect(self.actionSave) self.aNewProject.triggered.connect(self.actionNewProject) self.pbAddBox.clicked.connect(self.addBox) self.pbDeleteBox.clicked.connect(self.deleteBox) self.cbSelectBox.activated.connect(self.cbSwitch) self.slScale.valueChanged.connect(self.slScaleChange) self.slResolution.valueChanged.connect(self.slResolutionChange) self.aOpen.triggered.connect(self.actionOpen) for (key, button) in self.turn_buttons.items(): button.clicked.connect(partial(self.turn, key)) for (key, button) in self.swap_buttons.items(): button.clicked.connect(partial(self.swap, key)) def actionNewProject(self): self.blocks.clear() self.current_block = 0 self.cbSelectBox.clear() self.sendCurrentBlock(0) self.block_count = 0 self.update() def actionExport(self): if using_qt5: export_as = QFileDialog.getSaveFileName(self, "Export as...")[0] else: export_as = QFileDialog.getSaveFileName(self, "Export as...") create_code = codegen.codegen(self, "mynode", self.blocks, self.resolution) if export_as != "": create_code.writeToFile(export_as) def actionSave(self): if using_qt5: save_as = QFileDialog.getSaveFileName(self, "Save as...")[0] else: save_as = QFileDialog.getSaveFileName(self, "Save as...") if save_as != "": output_file = open(save_as, "w+") for b in self.blocks: output_file.write(" ".join([ str(b.p1()[0]), str(b.p1()[2]), str(b.p1()[1]), str(b.p2()[0]), str(b.p2()[2]), str(b.p2()[1])]) + "\n") output_file.close() def sendCurrentBlock(self, block): for view in self.views.values(): view.set_current_block(block) def sendScale(self, scale): for view in self.views.values(): view.set_scale(scale) self.gvMain.scale = scale def sendResolution(self, resolution): for view in self.views.values(): view.set_resolution(resolution) self.gvMain.resolution = resolution self.resolution = resolution def actionOpen(self): if using_qt5: open_from = QFileDialog.getOpenFileName(self, "Open file")[0] else: open_from = QFileDialog.getOpenFileName(self, "Open file") input_file = open(open_from, "r") self.blocks.clear() self.sendCurrentBlock(0) self.cbSelectBox.clear() for line in input_file: t = [int(token) for token in line.split(" ")] self.blocks.append(Block([t[0], t[2], t[1], 1], [t[3], t[5], t[4], 1])) self.cbSelectBox.addItems(["Block" + str(len(self.blocks))]) input_file.close() self.update() def cbSwitch(self): self.current_block = self.blocks[self.cbSelectBox.currentIndex()] self.sendCurrentBlock(self.current_block) self.update() def slScaleChange(self): self.sendScale(self.slScale.value()) self.update() def slResolutionChange(self): self.sendResolution(2**self.slResolution.value()) self.update() def swap(self, coords): for b in self.blocks: b.swap(coords) self.update() def turn(self, coord): for b in self.blocks: b.turn(coord) self.update()
class AvailableSizes(QDialog): def __init__(self): super(AvailableSizes, self).__init__() self.createCombos() self.createHeader() #self.createMenuBar() self.printOut = QTextEdit() self.printOut.setFont(QFont('Helvetica', 11, QFont.Bold)) self.printOut.setReadOnly(True) mainLayout = QVBoxLayout() #mainLayout.setMenuBar(self.menuBar) mainLayout.addWidget(self.frmHeader) mainLayout.addWidget(self.grpBox) mainLayout.addWidget(self.printOut) #mainLayout.setAlignment(self.frmHeader, Qt.AlignRight) self.setLayout(mainLayout) #self.setWindowTitle("Available Sizes") self.setWindowFlags(Qt.FramelessWindowHint) bgColor = QPalette() bgColor.setColor(self.backgroundRole(), Qt.gray) self.setPalette(bgColor) self.setWindowIcon(QIcon('icon/PS_Icon.png')) self.cbSku.setFocus() def createHeader(self): blk = QPalette() blk.setColor(blk.Foreground, Qt.white) lblTitle = QLabel("Availability Checker") lblTitle.setFont(QFont("Times", 12, QFont.Bold )) lblTitle.setPalette(blk) btnClose = QToolButton() btnClose.setIcon(QIcon("icon\size_exit.png")) btnClose.setAutoRaise(True) btnClose.setIconSize(QSize(25,25)) btnClose.clicked.connect(lambda: self.close()) hbHeader = QHBoxLayout() hbHeader.addWidget(lblTitle) hbHeader.addWidget(btnClose) hbHeader.setContentsMargins(0, 0, 0, 0) self.frmHeader = QFrame() self.frmHeader.setLayout(hbHeader) def createCombos(self): cbFont = QFont("Times", 8, QFont.Bold) designs = self.getDesigns() self.grpBox = QGroupBox() self.grpBox.setFont(QFont('Times', 10, QFont.Bold)) layout = QFormLayout() self.cbSku = QComboBox() self.cbSku.addItem("Designs") self.cbSku.addItems(designs) self.cbSku.setFont(cbFont) self.cbSku.currentIndexChanged.connect(self.skuChanged) self.cbStyle = QComboBox() self.cbStyle.addItem("Styles") self.cbStyle.setFont(cbFont) self.cbStyle.currentIndexChanged.connect(self.styleChanged) layout.addRow(QLabel("Design:"), self.cbSku) layout.addRow(QLabel("Style:"), self.cbStyle) self.grpBox.setLayout(layout) def skuChanged(self): if self.cbStyle.count() > 0: self.cbStyle.clear() self.cbStyle.addItem("Style") self.cbStyle.setCurrentIndex(0) styles = self.getStyles(self.cbSku.currentText()) else: styles = self.getStyles(self.cbSku.currentText()) self.cbStyle.addItems(styles) def styleChanged(self): self.printOut.clear() sizes = self.getSizes(self.cbSku.currentText(), self.cbStyle.currentText()) if self.cbStyle.currentText() != "Styles": for i in sizes: self.printOut.insertPlainText(i + '\n') def createMenuBar(self): self.menuBar = QMenuBar() self.fileMenu = QMenu("&File", self) self.exitAction = self.fileMenu.addAction("E&xit") self.menuBar.addMenu(self.fileMenu) self.exitAction.triggered.connect(self.accept) def getDesigns(self): sd = mysql_db.mysql_connect(self) sd.execute("""SELECT DISTINCT CONCAT(d.sku_code, " - ", d.name) design FROM designs d JOIN packages p on p.design_id = d.id ORDER BY RIGHT(d.sku_code, 3), LEFT(d.sku_code,1)""") ds = sd.fetchall() lsDesigns = [] for i in ds: lsDesigns.append(i[0]) return lsDesigns def getStyles(self, sku): sd = mysql_db.mysql_connect(self) sd.execute("""SELECT DISTINCT g.name FROM garment_styles_ages g JOIN packages p ON p.garment_styles_age_id = g.id JOIN designs d ON d.id = p.design_id WHERE d.sku_code = '""" + sku[:4] + """' ORDER BY g.name""") ds = sd.fetchall() lsStyles = [] for i in ds: lsStyles.append(i[0]) return lsStyles def getSizes(self, sku, style): style = style.replace("'", "\\'") sd = mysql_db.mysql_connect(self) sd.execute(""" SELECT DISTINCT CONCAT(s.name, ' - ', c.name) size FROM sizes s JOIN packages p ON p.size_id = s.id JOIN designs d ON d.id = p.design_id JOIN colors c ON c.id = p.color_id JOIN garment_styles_ages g ON g.id = p.garment_styles_age_id WHERE d.sku_code = '""" + sku[:4] + """' AND g.name = '""" + style + """'""") ds = sd.fetchall() lsSizes = [] for i in ds: lsSizes.append(i[0]) return lsSizes def mousePressEvent(self, event): if event.button() == Qt.LeftButton: self.leftClick = True self.offset = event.pos() def mouseMoveEvent(self, event): if self.leftClick == True: x=event.globalX() y=event.globalY() x_w = self.offset.x() y_w = self.offset.y() self.move(x-x_w, y-y_w) def mouseReleaseEvent(self, event): self.leftClick = False
class GlobalMenu(QWidget): new_window_signal = pyqtSignal() rename_signal = pyqtSignal() file_signal = pyqtSignal() drawer_signal = pyqtSignal() clean_up_signal = pyqtSignal() delete_signal = pyqtSignal() trash_action_signal = pyqtSignal() def __init__(self, parent=None): super(GlobalMenu, self).__init__(parent) self.menubar = QMenuBar() file_menu = self.menubar.addMenu('File') edit_menu = self.menubar.addMenu('Edit') about_action = QAction('About', self) preferences_action = QAction('Preferences', self) preferences_action.setShortcut('Ctrl+Shift+P') quit_action = QAction('Quit', self) quit_action.setShortcut('Ctrl+Q') file_action = QAction('Create file', self) file_action.setShortcut('Ctrl+Shift+N') drawer_action = QAction('Create drawer', self) drawer_action.setShortcut('Ctrl+N') requester_action = QAction('Requester', self) requester_action.setShortcut('Ctrl+O') parent_action = QAction('Open Parent', self) parent_action.setShortcut('Ctrl+P') info_action = QAction('Get info', self) info_action.setShortcut('Ctrl+I') rename_action = QAction('Rename', self) rename_action.setShortcut('Ctrl+R') copy_action = QAction('Copy', self) copy_action.setShortcut('Ctrl+C') paste_action = QAction('Paste', self) paste_action.setShortcut('Ctrl+V') clean_action = QAction('Clean Up', self) clean_action.setShortcut('Ctrl+;') delete_action = QAction('Move to Trash', self) delete_action.setShortcut('Ctrl+Backspace') trash_action = QAction('Empty trash', self) trash_action.setShortcut('Ctrl+Shift+Backspace') preferences_action.triggered.connect(self.preferences_action) quit_action.triggered.connect(self.quit_action) requester_action.triggered.connect(self.requester_action) parent_action.triggered.connect(self.parent_action) file_action.triggered.connect(self.file_action) drawer_action.triggered.connect(self.drawer_action) rename_action.triggered.connect(self.rename_action) clean_action.triggered.connect(self.clean_action) delete_action.triggered.connect(self.delete_action) trash_action.triggered.connect(self.trash_action) file_menu.addAction(requester_action) file_menu.addAction(parent_action) file_menu.addAction(info_action) file_menu.addAction(about_action) file_menu.addAction(quit_action) edit_menu.addAction(preferences_action) edit_menu.addAction(file_action) edit_menu.addAction(drawer_action) edit_menu.addAction(rename_action) edit_menu.addAction(copy_action) edit_menu.addAction(paste_action) edit_menu.addAction(clean_action) edit_menu.addAction(delete_action) edit_menu.addAction(trash_action) def quit_action(self): print("quit action menu") sys.exit(0) def preferences_action(self): print("preference action menu") QProcess.startDetached("./prefs.py") def requester_action(self): print("requester action menu") QProcess.startDetached("./requester.py") def parent_action(self): print("parent action menu") self.new_window_signal.emit() def file_action(self): print("file action menu") self.file_signal.emit() def drawer_action(self): print("drawer action menu") self.drawer_signal.emit() def rename_action(self): print("rename action menu") self.rename_signal.emit() def clean_action(self): print("clean up menu") self.clean_up_signal.emit() def delete_action(self): print("delete action menu") self.delete_signal.emit() def trash_action(self): print("empty trash action menu") self.empty_trash_action.signal.emit()
class PDFAreaSelectorDlg(QDialog): def __init__(self, parent=None): super().__init__(parent) self._parent = parent self.setWindowTitle("Area selection") self.scaleFactor = 1 self.setModal(True) self.controlBarWgt = QWidget(self) self.nextPageBtn = QPushButton("Next page (Ctrl+right arrow)") self.previousPageBtn = QPushButton("Previous page (Ctrl+left arrow)") self.noPageTxt = QLabel("1") self.noPageTxt.setStyleSheet("border: 1px solid grey") self.noPageTxt.setFixedWidth(40) self.controlBarWgt.setLayout(QHBoxLayout()) self.nextPageBtn.clicked.connect(self.nextPage) self.previousPageBtn.clicked.connect(self.previousPage) self.controlBarWgt.layout().addWidget(self.previousPageBtn) self.controlBarWgt.layout().addWidget(self.noPageTxt) self.controlBarWgt.layout().addWidget(self.nextPageBtn) self.imageLabel = ImageWidget() self.imageLabel.setBackgroundRole(QPalette.Base) self.imageLabel.setSizePolicy(QSizePolicy.Ignored, QSizePolicy.Ignored) self.imageLabel.setScaledContents(True) self.scrollArea = QScrollArea() self.scrollArea.setBackgroundRole(QPalette.Dark) self.scrollArea.setWidget(self.imageLabel) self.createActions() self.createMenus() self.setLayout(QVBoxLayout()) self.layout().addWidget(self.menuBar) self.layout().addWidget(self.controlBarWgt) self.layout().addWidget(self.scrollArea) self.imageLabel.areaSelected.connect(self.resendSelectedEvent) self.loadImage() @pyqtSlot(float, float, float, float, QPixmap) def resendSelectedEvent(self, x, y, width, height, image): self._parent.x = x self._parent.y = y self._parent.width = width self._parent.height = height self._parent.image = image self._parent.areaSelected.emit() self.close() def loadImage(self): image = QImage.fromData(self._parent.pages[self._parent.currentPageInd],"PNG") self.imageLabel.setPixmap(QPixmap.fromImage(image)) self.fitToWindowAct.setEnabled(True) self.updateActions() if not self.fitToWindowAct.isChecked(): self.imageLabel.adjustSize() self.setWindowFilePath(self._parent.fileName) return True def zoomIn(self): self.scaleImage(1.25) def zoomOut(self): self.scaleImage(0.8) def normalSize(self): self.imageLabel.adjustSize() self.scaleFactor = 1.0 def fitToWindow(self): fitToWindow = self.fitToWindowAct.isChecked() self.scrollArea.setWidgetResizable(fitToWindow) if not fitToWindow : self.normalSize() self.updateActions() def createActions(self): self.exitAct = QAction("E&xit", self) self.exitAct.setShortcut("Ctrl+Q") self.exitAct.triggered.connect(self.close) self.zoomInAct = QAction("Zoom &In (25%)", self) self.zoomInAct.setShortcut("Ctrl++") self.zoomInAct.setEnabled(False) self.zoomInAct.triggered.connect(self.zoomIn) self.zoomOutAct = QAction("Zoom &Out (25%)", self) self.zoomOutAct.setShortcut("Ctrl+-") self.zoomOutAct.setEnabled(False) self.zoomOutAct.triggered.connect(self.zoomOut) self.normalSizeAct = QAction("&Normal Size", self) self.normalSizeAct.setShortcut("Ctrl+S") self.normalSizeAct.setEnabled(False) self.normalSizeAct.triggered.connect(self.normalSize) self.fitToWindowAct = QAction("&Fit to Window", self) self.fitToWindowAct.setEnabled(False) self.fitToWindowAct.setCheckable(True) self.fitToWindowAct.setShortcut("Ctrl+F") self.fitToWindowAct.triggered.connect(self.fitToWindow) self.nextPageAct = QAction("&Next page", self) self.nextPageAct.setEnabled(True) self.nextPageAct.setShortcut(QKeySequence(Qt.CTRL + Qt.Key_Right)) self.nextPageAct.triggered.connect(self.nextPage) self.previousPageAct = QAction("&Previous page", self) self.previousPageAct.setEnabled(True) self.previousPageAct.setShortcut(QKeySequence(Qt.CTRL + Qt.Key_Left)) self.previousPageAct.triggered.connect(self.previousPage) def createMenus(self): self.menuBar = QMenuBar(self) self.fileMenu = QMenu("&File", self) self.fileMenu.addAction(self.exitAct) self.viewMenu = QMenu("&View", self) self.viewMenu.addAction(self.zoomInAct) self.viewMenu.addAction(self.zoomOutAct) self.viewMenu.addAction(self.normalSizeAct) self.viewMenu.addSeparator() self.viewMenu.addAction(self.fitToWindowAct) self.viewMenu.addSeparator() self.viewMenu.addAction(self.nextPageAct) self.viewMenu.addAction(self.previousPageAct) self.menuBar.addMenu(self.fileMenu) self.menuBar.addMenu(self.viewMenu) def updateActions(self): self.zoomInAct.setEnabled(not self.fitToWindowAct.isChecked()) self.zoomOutAct.setEnabled(not self.fitToWindowAct.isChecked()) self.normalSizeAct.setEnabled(not self.fitToWindowAct.isChecked()) def scaleImage(self, factor): assert(self.imageLabel.pixmap()) self.scaleFactor *= factor self.imageLabel.resize(self.scaleFactor * self.imageLabel.pixmap().size()) self.adjustScrollBar(self.scrollArea.horizontalScrollBar(), factor) self.adjustScrollBar(self.scrollArea.verticalScrollBar(), factor) self.zoomInAct.setEnabled(self.scaleFactor < 3.0) self.zoomOutAct.setEnabled(self.scaleFactor > 0.333) def adjustScrollBar(self, scrollBar, factor): scrollBar.setValue(int(factor * scrollBar.value() + ((factor - 1) * scrollBar.pageStep()/2))) def nextPage(self): if self._parent.currentPageInd < len(self._parent.pages)-1: self._parent.currentPageInd += 1 self.loadImage() self.noPageTxt.setText(str(self._parent.currentPageInd+1)) def previousPage(self): if self._parent.currentPageInd > 0: self._parent.currentPageInd -= 1 self.loadImage() self.noPageTxt.setText(str(self._parent.currentPageInd+1))
class QMW(QMainWindow): NumGridRows = 1 def __init__(self): super(QMW, self).__init__() self.tableau = TableauQt("x") self.simple = False # doit-on faire un tableau simplifié # symboles unicode 2a7d et 2a7e voir # http://fr.wikipedia.org/wiki/Table_des_caract%C3%A8res_Unicode_%282000-2FFF%29#Fl.C3.A8ches self.inequations = {"⩽0": "-0", "<0": "--", "⩾0": "+0", ">0": "++"} self.createMenu() self.createHorizontalGroupBox() self.createFormGroupBox() self.createBoundBox() self.createSolutionBox() self.exitAct = QAction( "E&xit", self, shortcut="Ctrl+Q", statusTip="Sortir de l'application", triggered=self.close ) bigEditor = QTextEdit() bigEditor.setPlainText("Création de la sortie latex ici pour un copier/coller ") buttonBox = QDialogButtonBox(QDialogButtonBox.Ok) # | QDialogButtonBox.Cancel buttonBox.accepted.connect(self.close) widget = QWidget() self.setCentralWidget(widget) mainLayout = QVBoxLayout() mainLayout.setMenuBar(self.menuBar) mainLayout.addWidget(self.formGroupBox) mainLayout.addWidget(self.BoundBox) mainLayout.addWidget(bigEditor) mainLayout.addWidget(self.solGroupBox) mainLayout.addWidget(self.horizontalGroupBox) mainLayout.addWidget(buttonBox) widget.setLayout(mainLayout) self.bigEditor = bigEditor self.setWindowTitle("Tableau de signe") @pyqtSlot() def _createApropos(self): QMessageBox.information( self, "À propos", "<p><strong>Tableau de signe</strong> - v" + __version__ + "</p>" + "<p>B. Mauricette - GPLv3</p>", ) def createMenu(self): self.menuBar = QMenuBar() self.fileMenu = QMenu("&Fichier", self) self.exitAction = self.fileMenu.addAction("E&xit") apropos = QMenu("&Infos", self) apro = QAction("À &propos", self) apro.triggered.connect(self._createApropos) apropos.addAction(apro) self.menuBar.addMenu(self.fileMenu) self.menuBar.addMenu(apropos) def createBoundBox(self): self.BoundBox = QGroupBox("Bornes") layout = QHBoxLayout() self.b_inf = QLineEdit(str(self.tableau.bornes[0])) self.b_inf.editingFinished.connect(self._update_inf) # self.b_inf.editingFinished.emit(self.b_inf.text()) self.b_sup = QLineEdit(str(self.tableau.bornes[1])) self.b_sup.editingFinished.connect(self._update_sup) # self.b_sup.editingFinished.emit(self.b_sup.text()) layout.addWidget(QLabel("borne inf :")) layout.addWidget(self.b_inf) layout.addWidget(QLabel("borne sup :")) layout.addWidget(self.b_sup) self.BoundBox.setLayout(layout) @pyqtSlot() def _update_inf(self): """ màj de la borne inférieure la valeur est sympifiée """ self.tableau.bornes[0] = sympify(self.b_inf.text()) self._createTableau() @pyqtSlot() def _update_sup(self): """ màj de la borne supérieure la valeur est sympifiée """ self.tableau.bornes[1] = sympify(self.b_sup.text()) self._createTableau() def createHorizontalGroupBox(self): self.horizontalGroupBox = QGroupBox("Export") layout = QHBoxLayout() out = [("LaTeX", self._export_latex), ("PST+", self._export_pst), ("PAG", self._export_pag)] for i in range(len(out)): button = QPushButton(out[i][0]) button.clicked.connect(out[i][1]) layout.addWidget(button) self.horizontalGroupBox.setLayout(layout) @pyqtSlot() def _export_latex(self): fichier = QFileDialog.getSaveFileName( self, "Enregistrer sous…", "/home/boris/Documents/tableau.tex", "Fichiers LaTeX (*.tex)" ) self.tableau.export(fichier, simplif=self.simple) @pyqtSlot() def _export_pst(self): fichier = QFileDialog.getSaveFileName( self, "Enregistrer sous…", "/home/boris/Documents/tableau.pst", "Fichiers PST+ (*.pst)" ) self.tableau.export(fichier, simplif=self.simple) @pyqtSlot() def _export_pag(self): fichier = QFileDialog.getSaveFileName(self, "Enregistrer sous…", "tableau.pag", "Fichiers PAG (PdfAdd) (*.pag)") self.tableau.export(fichier, simplif=self.simple) def createFormGroupBox(self): self.formGroupBox = QGroupBox("Entrée") simple = QCheckBox("Simplifier (pas de lignes intermédiaires)") # bool à basculer simple.clicked.connect(self._simple) self.expression = QLineEdit(str(self.tableau.expr)) layout = QFormLayout() layout.addRow(QLabel("(fraction rationnelle):"), self.expression) valid = QPushButton("Valider") valid.clicked.connect(self._createTableau) layout.addWidget(valid) layout.addWidget(simple) self.formGroupBox.setLayout(layout) def _simple(self): self.simple = not (self.simple) self._createTableau() def _createTableau(self): ex = self.expression.text() # créer un nouveau TableauQt provoquerait des pointeurs d'actions vides self.tableau.__init__(ex) self.bigEditor.setPlainText(self.tableau.tab2latex(simplif=self.simple)) # voir self.inequations dans __init__ ineq = self.inequations[self.choixIneq.currentText()] self.solution.setText(self.tableau.get_solutions(ineq)) def _fillbis(self, t): """récupérer l'émission du signal lors d'un changement d'inéquation """ self.solution.setText(self.tableau.get_solutions(self.inequations[t])) def createSolutionBox(self): self.solGroupBox = QGroupBox("Ensemble des solutions d'inéquation") self.solution = QLineEdit() layout = QFormLayout() choix = QComboBox() # for x in ["<=0","<0", ">=0",">0"] for x in self.inequations.keys(): choix.addItem(x) self.choixIneq = choix # associer le signal de changement d'inéquation au slot de self.solution.setText self.choixIneq.currentTextChanged.connect(self._fillbis) self.choixIneq.currentTextChanged.emit(self.choixIneq.currentText()) layout.addRow(QLabel("Inéquation de la forme f(x)"), self.choixIneq) layout.addRow(QLabel("ens. des solutions:"), self.solution) self.solGroupBox.setLayout(layout)
def ui(self): menubar = QMenuBar() menubar.setNativeMenuBar(True) # make the menu bar OS specific bar_file = menubar.addMenu(self.tr("&File")) file_load = QAction(self.tr("&Load image"), self, shortcut=QKeySequence.New, statusTip=self.tr("Load a new image"), triggered=self.open_file) file_save = QAction(self.tr("&Save plate"), self, shortcut=QKeySequence.Save, statusTip=self.tr("Save the pattern"), triggered=self.save_file) file_print = QAction(self.tr("&Print"), self, shortcut=QKeySequence.Print, statusTip=self.tr("Print pixel pattern"), triggered=self.print_file) file_settings = QAction(self.tr("S&ettings"), self, statusTip=self.tr('Change settings'), triggered=self.change_settings) file_quit = QAction(self.tr("&Quit"), self, shortcut=QKeySequence.Quit, statusTip=self.tr('Quit the program'), triggered=self.close) bar_file.addAction(file_load) bar_file.addAction(file_save) bar_file.addAction(file_print) bar_file.addAction(file_settings) bar_file.addAction(file_quit) bar_about = menubar.addMenu(self.tr("&About")) about_about = QAction(self.tr("&About"), self, statusTip=self.tr("Show about PyBigPix"), triggered=self.show_about) about_licence = QAction(self.tr("&License"), self, statusTip=self.tr('Show license'), triggered=self.show_license) about_QT = QAction(self.tr("About &QT"), self, statusTip=self.tr("Show about QT"), triggered=qApp.aboutQt) bar_about.addAction(about_about) bar_about.addAction(about_licence) bar_about.addAction(about_QT) self.setMenuWidget(menubar) self.setMenuBar(menubar) self.setWindowTitle(self.window_title) self.label_image = QLabel(self.tr("Start Image")) self.label_image.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) self.label_image.setMinimumSize(400, 400) self.label_image.textFormat() self.label_image.setFrameShape(QFrame.Panel) self.label_image.setAlignment(Qt.AlignCenter) self.lable_pixels = QLabel(self.tr("Pixel Image")) self.lable_pixels.setMinimumSize(400, 400) self.lable_pixels.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) self.lable_pixels.setAlignment(Qt.AlignCenter) self.lable_pixels.setFrameShape(QFrame.Panel) self.centeralwidget = QWidget() layout = QHBoxLayout(self.centeralwidget) layout.addWidget(self.label_image) layout.addWidget(self.lable_pixels) self.setCentralWidget(self.centeralwidget)
def init(self): QWidget.__init__(self) self.win_list=windows() self.win_list.load() self.win_list.set_window(self,"fit_window") self.main_vbox = QVBoxLayout() menubar = QMenuBar() file_menu = menubar.addMenu('&File') self.menu_close=file_menu.addAction(_("Close")) self.menu_close.triggered.connect(self.callback_close) self.menu_fit=menubar.addMenu(_("Fits")) self.menu_fit_new=self.menu_fit.addAction(_("&New")) self.menu_fit_new.triggered.connect(self.callback_add_page) self.menu_fit_delete=self.menu_fit.addAction(_("&Delete fit")) self.menu_fit_delete.triggered.connect(self.callback_delete_page) self.menu_fit_rename=self.menu_fit.addAction(_("&Rename fit")) self.menu_fit_rename.triggered.connect(self.callback_rename_page) self.menu_fit_import=self.menu_fit.addAction(_("&Import data")) self.menu_fit_import.triggered.connect(self.callback_import) self.menu_fit_clone=self.menu_fit.addAction(_("&Clone fit")) self.menu_fit_clone.triggered.connect(self.callback_copy_page) self.menu_help=menubar.addMenu(_("Help")) self.menu_help_help=self.menu_help.addAction(_("Help")) self.menu_help_help.triggered.connect(self.callback_help) self.main_vbox.addWidget(menubar) #self.setFixedSize(900, 700) self.setWindowTitle(_("Fit window - gpvdm")) self.setWindowIcon(QIcon(os.path.join(get_image_file_path(),"fit.png"))) toolbar=QToolBar() toolbar.setIconSize(QSize(48, 48)) self.new = QAction(QIcon(os.path.join(get_image_file_path(),"new.png")), _("New laser"), self) self.new.triggered.connect(self.callback_add_page) toolbar.addAction(self.new) self.new = QAction(QIcon(os.path.join(get_image_file_path(),"delete.png")), _("Delete laser"), self) self.new.triggered.connect(self.callback_delete_page) toolbar.addAction(self.new) self.clone = QAction(QIcon(os.path.join(get_image_file_path(),"clone.png")), _("Clone laser"), self) self.clone.triggered.connect(self.callback_copy_page) toolbar.addAction(self.clone) self.clone = QAction(QIcon(os.path.join(get_image_file_path(),"rename.png")), _("Rename laser"), self) self.clone.triggered.connect(self.callback_rename_page) toolbar.addAction(self.clone) self.import_data= QAction(QIcon(os.path.join(get_image_file_path(),"import.png")), _("Import data"), self) self.import_data.triggered.connect(self.callback_import) toolbar.addAction(self.import_data) self.play= QAction(QIcon(os.path.join(get_image_file_path(),"play.png")), _("Run a single fit"), self) self.play.triggered.connect(self.callback_import) toolbar.addAction(self.play) self.play= QAction(QIcon(os.path.join(get_image_file_path(),"forward.png")), _("Start the fitting process"), self) self.play.triggered.connect(self.callback_do_fit) toolbar.addAction(self.play) spacer = QWidget() spacer.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) toolbar.addWidget(spacer) self.help = QAction(QIcon(os.path.join(get_image_file_path(),"help.png")), 'Help', self) self.help.triggered.connect(self.callback_help) toolbar.addAction(self.help) self.main_vbox.addWidget(toolbar) self.notebook = QTabWidget() self.notebook.setTabBar(QHTabBar()) self.notebook.setTabPosition(QTabWidget.West) self.notebook.setMovable(True) self.load_tabs() self.main_vbox.addWidget(self.notebook) self.status_bar=QStatusBar() self.main_vbox.addWidget(self.status_bar) self.setLayout(self.main_vbox) return
def __init__(self, parent=None): QMainWindow.__init__(self, parent) self.resize(950, 700) screenRect = QDesktopWidget().screenGeometry() if globalSettings.windowGeometry: self.restoreGeometry(globalSettings.windowGeometry) else: self.move((screenRect.width()-self.width())/2, (screenRect.height()-self.height())/2) if not screenRect.contains(self.geometry()): self.showMaximized() if globalSettings.iconTheme: QIcon.setThemeName(globalSettings.iconTheme) if QIcon.themeName() in ('hicolor', ''): if not QFile.exists(icon_path + 'document-new.png'): QIcon.setThemeName(get_icon_theme()) if QFile.exists(icon_path+'retext.png'): self.setWindowIcon(QIcon(icon_path+'retext.png')) elif QFile.exists('/usr/share/pixmaps/retext.png'): self.setWindowIcon(QIcon('/usr/share/pixmaps/retext.png')) else: self.setWindowIcon(QIcon.fromTheme('retext', QIcon.fromTheme('accessories-text-editor'))) self.tabWidget = QTabWidget(self) self.initTabWidget() self.setCentralWidget(self.tabWidget) self.tabWidget.currentChanged.connect(self.changeIndex) self.tabWidget.tabCloseRequested.connect(self.closeTab) toolBar = QToolBar(self.tr('File toolbar'), self) self.addToolBar(Qt.TopToolBarArea, toolBar) self.editBar = QToolBar(self.tr('Edit toolbar'), self) self.addToolBar(Qt.TopToolBarArea, self.editBar) self.searchBar = QToolBar(self.tr('Search toolbar'), self) self.addToolBar(Qt.BottomToolBarArea, self.searchBar) toolBar.setVisible(not globalSettings.hideToolBar) self.editBar.setVisible(not globalSettings.hideToolBar) self.actionNew = self.act(self.tr('New'), 'document-new', self.createNew, shct=QKeySequence.New) self.actionNew.setPriority(QAction.LowPriority) self.actionOpen = self.act(self.tr('Open'), 'document-open', self.openFile, shct=QKeySequence.Open) self.actionOpen.setPriority(QAction.LowPriority) self.actionSetEncoding = self.act(self.tr('Set encoding'), trig=self.showEncodingDialog) self.actionSetEncoding.setEnabled(False) self.actionReload = self.act(self.tr('Reload'), 'view-refresh', trig=self.openFileMain) self.actionReload.setEnabled(False) self.actionSave = self.act(self.tr('Save'), 'document-save', self.saveFile, shct=QKeySequence.Save) self.actionSave.setEnabled(False) self.actionSave.setPriority(QAction.LowPriority) self.actionSaveAs = self.act(self.tr('Save as'), 'document-save-as', self.saveFileAs, shct=QKeySequence.SaveAs) self.actionNextTab = self.act(self.tr('Next tab'), 'go-next', lambda: self.switchTab(1), shct=Qt.CTRL+Qt.Key_PageDown) self.actionPrevTab = self.act(self.tr('Previous tab'), 'go-previous', lambda: self.switchTab(-1), shct=Qt.CTRL+Qt.Key_PageUp) self.actionPrint = self.act(self.tr('Print'), 'document-print', self.printFile, shct=QKeySequence.Print) self.actionPrint.setPriority(QAction.LowPriority) self.actionPrintPreview = self.act(self.tr('Print preview'), 'document-print-preview', self.printPreview) self.actionViewHtml = self.act(self.tr('View HTML code'), 'text-html', self.viewHtml) self.actionChangeEditorFont = self.act(self.tr('Change editor font'), trig=self.changeEditorFont) self.actionChangePreviewFont = self.act(self.tr('Change preview font'), trig=self.changePreviewFont) self.actionSearch = self.act(self.tr('Find text'), 'edit-find', shct=QKeySequence.Find) self.actionSearch.setCheckable(True) self.actionSearch.triggered[bool].connect(self.searchBar.setVisible) self.searchBar.visibilityChanged.connect(self.searchBarVisibilityChanged) self.actionPreview = self.act(self.tr('Preview'), shct=Qt.CTRL+Qt.Key_E, trigbool=self.preview) if QIcon.hasThemeIcon('document-preview'): self.actionPreview.setIcon(QIcon.fromTheme('document-preview')) elif QIcon.hasThemeIcon('preview-file'): self.actionPreview.setIcon(QIcon.fromTheme('preview-file')) elif QIcon.hasThemeIcon('x-office-document'): self.actionPreview.setIcon(QIcon.fromTheme('x-office-document')) else: self.actionPreview.setIcon(QIcon(icon_path+'document-preview.png')) self.actionLivePreview = self.act(self.tr('Live preview'), shct=Qt.CTRL+Qt.Key_L, trigbool=self.enableLivePreview) menuPreview = QMenu() menuPreview.addAction(self.actionLivePreview) self.actionPreview.setMenu(menuPreview) self.actionTableMode = self.act(self.tr('Table mode'), shct=Qt.CTRL+Qt.Key_T, trigbool=lambda x: self.currentTab.editBox.enableTableMode(x)) if ReTextFakeVimHandler: self.actionFakeVimMode = self.act(self.tr('FakeVim mode'), shct=Qt.CTRL+Qt.ALT+Qt.Key_V, trigbool=self.enableFakeVimMode) if globalSettings.useFakeVim: self.actionFakeVimMode.setChecked(True) self.enableFakeVimMode(True) self.actionFullScreen = self.act(self.tr('Fullscreen mode'), 'view-fullscreen', shct=Qt.Key_F11, trigbool=self.enableFullScreen) self.actionFullScreen.setPriority(QAction.LowPriority) self.actionConfig = self.act(self.tr('Preferences'), icon='preferences-system', trig=self.openConfigDialog) self.actionConfig.setMenuRole(QAction.PreferencesRole) self.actionSaveHtml = self.act('HTML', 'text-html', self.saveFileHtml) self.actionPdf = self.act('PDF', 'application-pdf', self.savePdf) self.actionOdf = self.act('ODT', 'x-office-document', self.saveOdf) self.getExportExtensionsList() self.actionQuit = self.act(self.tr('Quit'), 'application-exit', shct=QKeySequence.Quit) self.actionQuit.setMenuRole(QAction.QuitRole) self.actionQuit.triggered.connect(self.close) self.actionUndo = self.act(self.tr('Undo'), 'edit-undo', lambda: self.currentTab.editBox.undo(), shct=QKeySequence.Undo) self.actionRedo = self.act(self.tr('Redo'), 'edit-redo', lambda: self.currentTab.editBox.redo(), shct=QKeySequence.Redo) self.actionCopy = self.act(self.tr('Copy'), 'edit-copy', lambda: self.currentTab.editBox.copy(), shct=QKeySequence.Copy) self.actionCut = self.act(self.tr('Cut'), 'edit-cut', lambda: self.currentTab.editBox.cut(), shct=QKeySequence.Cut) self.actionPaste = self.act(self.tr('Paste'), 'edit-paste', lambda: self.currentTab.editBox.paste(), shct=QKeySequence.Paste) self.actionUndo.setEnabled(False) self.actionRedo.setEnabled(False) self.actionCopy.setEnabled(False) self.actionCut.setEnabled(False) qApp = QApplication.instance() qApp.clipboard().dataChanged.connect(self.clipboardDataChanged) self.clipboardDataChanged() if enchant_available: self.actionEnableSC = self.act(self.tr('Enable'), trigbool=self.enableSpellCheck) self.actionSetLocale = self.act(self.tr('Set locale'), trig=self.changeLocale) self.actionWebKit = self.act(self.tr('Use WebKit renderer'), trigbool=self.enableWebKit) self.actionWebKit.setChecked(globalSettings.useWebKit) self.actionShow = self.act(self.tr('Show directory'), 'system-file-manager', self.showInDir) self.actionFind = self.act(self.tr('Next'), 'go-next', self.find, shct=QKeySequence.FindNext) self.actionFindPrev = self.act(self.tr('Previous'), 'go-previous', lambda: self.find(back=True), shct=QKeySequence.FindPrevious) self.actionHelp = self.act(self.tr('Get help online'), 'help-contents', self.openHelp) self.aboutWindowTitle = self.tr('About ReText') self.actionAbout = self.act(self.aboutWindowTitle, 'help-about', self.aboutDialog) self.actionAbout.setMenuRole(QAction.AboutRole) self.actionAboutQt = self.act(self.tr('About Qt')) self.actionAboutQt.setMenuRole(QAction.AboutQtRole) self.actionAboutQt.triggered.connect(qApp.aboutQt) availableMarkups = markups.get_available_markups() if not availableMarkups: print('Warning: no markups are available!') self.defaultMarkup = availableMarkups[0] if availableMarkups else None if globalSettings.defaultMarkup: mc = markups.find_markup_class_by_name(globalSettings.defaultMarkup) if mc and mc.available(): self.defaultMarkup = mc if len(availableMarkups) > 1: self.chooseGroup = QActionGroup(self) markupActions = [] for markup in availableMarkups: markupAction = self.act(markup.name, trigbool=self.markupFunction(markup)) if markup == self.defaultMarkup: markupAction.setChecked(True) self.chooseGroup.addAction(markupAction) markupActions.append(markupAction) self.actionBold = self.act(self.tr('Bold'), shct=QKeySequence.Bold, trig=lambda: self.insertChars('**')) self.actionItalic = self.act(self.tr('Italic'), shct=QKeySequence.Italic, trig=lambda: self.insertChars('*')) self.actionUnderline = self.act(self.tr('Underline'), shct=QKeySequence.Underline, trig=lambda: self.insertTag('u')) self.usefulTags = ('a', 'big', 'center', 'img', 's', 'small', 'span', 'table', 'td', 'tr', 'u') self.usefulChars = ('deg', 'divide', 'dollar', 'hellip', 'laquo', 'larr', 'lsquo', 'mdash', 'middot', 'minus', 'nbsp', 'ndash', 'raquo', 'rarr', 'rsquo', 'times') self.tagsBox = QComboBox(self.editBar) self.tagsBox.addItem(self.tr('Tags')) self.tagsBox.addItems(self.usefulTags) self.tagsBox.activated.connect(self.insertTag) self.symbolBox = QComboBox(self.editBar) self.symbolBox.addItem(self.tr('Symbols')) self.symbolBox.addItems(self.usefulChars) self.symbolBox.activated.connect(self.insertSymbol) self.updateStyleSheet() menubar = QMenuBar(self) menubar.setGeometry(QRect(0, 0, 800, 25)) self.setMenuBar(menubar) menuFile = menubar.addMenu(self.tr('File')) menuEdit = menubar.addMenu(self.tr('Edit')) menuHelp = menubar.addMenu(self.tr('Help')) menuFile.addAction(self.actionNew) menuFile.addAction(self.actionOpen) self.menuRecentFiles = menuFile.addMenu(self.tr('Open recent')) self.menuRecentFiles.aboutToShow.connect(self.updateRecentFiles) menuFile.addMenu(self.menuRecentFiles) menuFile.addAction(self.actionShow) menuFile.addAction(self.actionSetEncoding) menuFile.addAction(self.actionReload) menuFile.addSeparator() menuFile.addAction(self.actionSave) menuFile.addAction(self.actionSaveAs) menuFile.addSeparator() menuFile.addAction(self.actionNextTab) menuFile.addAction(self.actionPrevTab) menuFile.addSeparator() menuExport = menuFile.addMenu(self.tr('Export')) menuExport.addAction(self.actionSaveHtml) menuExport.addAction(self.actionOdf) menuExport.addAction(self.actionPdf) if self.extensionActions: menuExport.addSeparator() for action, mimetype in self.extensionActions: menuExport.addAction(action) menuExport.aboutToShow.connect(self.updateExtensionsVisibility) menuFile.addAction(self.actionPrint) menuFile.addAction(self.actionPrintPreview) menuFile.addSeparator() menuFile.addAction(self.actionQuit) menuEdit.addAction(self.actionUndo) menuEdit.addAction(self.actionRedo) menuEdit.addSeparator() menuEdit.addAction(self.actionCut) menuEdit.addAction(self.actionCopy) menuEdit.addAction(self.actionPaste) menuEdit.addSeparator() if enchant_available: menuSC = menuEdit.addMenu(self.tr('Spell check')) menuSC.addAction(self.actionEnableSC) menuSC.addAction(self.actionSetLocale) menuEdit.addAction(self.actionSearch) menuEdit.addAction(self.actionChangeEditorFont) menuEdit.addAction(self.actionChangePreviewFont) menuEdit.addSeparator() if len(availableMarkups) > 1: self.menuMode = menuEdit.addMenu(self.tr('Default markup')) for markupAction in markupActions: self.menuMode.addAction(markupAction) menuFormat = menuEdit.addMenu(self.tr('Formatting')) menuFormat.addAction(self.actionBold) menuFormat.addAction(self.actionItalic) menuFormat.addAction(self.actionUnderline) menuEdit.addAction(self.actionWebKit) menuEdit.addSeparator() menuEdit.addAction(self.actionViewHtml) menuEdit.addAction(self.actionPreview) menuEdit.addAction(self.actionTableMode) if ReTextFakeVimHandler: menuEdit.addAction(self.actionFakeVimMode) menuEdit.addSeparator() menuEdit.addAction(self.actionFullScreen) menuEdit.addAction(self.actionConfig) menuHelp.addAction(self.actionHelp) menuHelp.addSeparator() menuHelp.addAction(self.actionAbout) menuHelp.addAction(self.actionAboutQt) menubar.addMenu(menuFile) menubar.addMenu(menuEdit) menubar.addMenu(menuHelp) toolBar.setToolButtonStyle(Qt.ToolButtonTextBesideIcon) toolBar.addAction(self.actionNew) toolBar.addSeparator() toolBar.addAction(self.actionOpen) toolBar.addAction(self.actionSave) toolBar.addAction(self.actionPrint) toolBar.addSeparator() toolBar.addAction(self.actionPreview) toolBar.addAction(self.actionFullScreen) self.editBar.addAction(self.actionUndo) self.editBar.addAction(self.actionRedo) self.editBar.addSeparator() self.editBar.addAction(self.actionCut) self.editBar.addAction(self.actionCopy) self.editBar.addAction(self.actionPaste) self.editBar.addSeparator() self.editBar.addWidget(self.tagsBox) self.editBar.addWidget(self.symbolBox) self.searchEdit = QLineEdit(self.searchBar) self.searchEdit.setPlaceholderText(self.tr('Search')) self.searchEdit.returnPressed.connect(self.find) self.csBox = QCheckBox(self.tr('Case sensitively'), self.searchBar) self.searchBar.addWidget(self.searchEdit) self.searchBar.addSeparator() self.searchBar.addWidget(self.csBox) self.searchBar.addAction(self.actionFindPrev) self.searchBar.addAction(self.actionFind) self.searchBar.setToolButtonStyle(Qt.ToolButtonTextBesideIcon) self.searchBar.setVisible(False) self.autoSaveEnabled = globalSettings.autoSave if self.autoSaveEnabled: timer = QTimer(self) timer.start(60000) timer.timeout.connect(self.saveAll) self.ind = None if enchant_available: self.sl = globalSettings.spellCheckLocale if self.sl: try: enchant.Dict(self.sl) except Exception as e: print(e, file=sys.stderr) self.sl = None if globalSettings.spellCheck: self.actionEnableSC.setChecked(True) self.enableSpellCheck(True) self.fileSystemWatcher = QFileSystemWatcher() self.fileSystemWatcher.fileChanged.connect(self.fileChanged)
class MainWindow_Ui(QMainWindow): def __init__(self): super().__init__() #MainWindow self.resize(600, 400) self.setMinimumSize(QSize(600, 400)) self.setMaximumSize(QSize(16777215, 16777215)) self.setWindowTitle("Persepolis Download Manager") self.setWindowIcon(QIcon('icon')) self.centralwidget = QWidget(self) self.verticalLayout = QVBoxLayout(self.centralwidget) #enable drag and drop self.setAcceptDrops(True) #frame self.frame = QFrame(self.centralwidget) self.frame.setGeometry(QRect(10, 10, 581, 251)) self.frame.setFrameShape(QFrame.StyledPanel) self.frame.setFrameShadow(QFrame.Raised) self.gridLayout = QGridLayout(self.frame) #tablewidget self.download_table = QTableWidget(self.frame) self.download_table.setGeometry(QRect(10, 10, 560, 231)) self.download_table.setSizeIncrement(QSize(0, 0)) self.download_table.setColumnCount(10) self.download_table.setSelectionBehavior(QAbstractItemView.SelectRows) self.download_table.setEditTriggers(QAbstractItemView.NoEditTriggers) self.download_table.verticalHeader().hide() self.download_table.setColumnHidden(8 , True) self.download_table.setColumnHidden(9 , True) self.gridLayout.addWidget(self.download_table, 0, 0, 1, 1) self.verticalLayout.addWidget(self.frame) self.setCentralWidget(self.centralwidget) download_table_header = ['File Name' , 'Status' , 'Size' , 'Downloaded' , 'Percentage' , 'Connections' , 'Transfer rate' , 'Estimate time left' , 'Gid' , 'Info'] self.download_table.setHorizontalHeaderLabels(download_table_header) #fixing the size of download_table when window is Maximized! self.download_table.horizontalHeader().setSectionResizeMode(0) self.download_table.horizontalHeader().setStretchLastSection(True) #finding number od row that user selected! self.download_table.itemSelectionChanged.connect(self.selectedRow) #menubar self.menubar = QMenuBar(self) self.menubar.setGeometry(QRect(0, 0, 600, 24)) self.setMenuBar(self.menubar) fileMenu = self.menubar.addMenu('File') editMenu = self.menubar.addMenu('Edit') viewMenu = self.menubar.addMenu('View') downloadMenu = self.menubar.addMenu('Download') helpMenu = self.menubar.addMenu('Help') #statusbar self.statusbar = QStatusBar(self) self.setStatusBar(self.statusbar) self.statusbar.showMessage("Persepolis Download Manager") #toolBar self.toolBar = QToolBar(self) self.addToolBar(QtCore.Qt.TopToolBarArea, self.toolBar) self.toolBar.setWindowTitle("toolBar") self.toolBar.setIconSize(QSize(38 , 38)) self.toolBar.setFloatable(False) self.toolBar.setMovable(False) #toolBar and menubar and actions self.stopAllAction = QAction(QIcon(icons + 'stop_all') , 'Stop all active downloads' , self , statusTip = 'Stop all active downloads', triggered = self.stopAllDownloads ) downloadMenu.addAction(self.stopAllAction) self.pauseAllAction = QAction(QIcon(icons + 'pause_all') , 'Pause all active downloads' , self , statusTip = 'Pause all active downloads', triggered = self.pauseAllDownloads ) downloadMenu.addAction(self.pauseAllAction) self.minimizeAction = QAction(QIcon(icons + 'minimize') , 'Minimize to system tray' , self , shortcut = "Ctrl+W" , statusTip = "Minimize to system tray" , triggered = self.minMaxTray) viewMenu.addAction(self.minimizeAction) self.addlinkAction = QAction(QIcon(icons + 'add') , 'Add New Download Link' , self , shortcut = "Ctrl+N" , statusTip = "Add New Download Link" , triggered = self.addLinkButtonPressed) fileMenu.addAction(self.addlinkAction) self.resumeAction = QAction(QIcon(icons + 'play') , 'Resume Download' , self , shortcut = "Ctrl+R" , statusTip = "Resume Download" , triggered = self.resumeButtonPressed) downloadMenu.addAction(self.resumeAction) self.pauseAction = QAction(QIcon(icons + 'pause') , 'Pause Download' , self , shortcut = "Ctrl+C" , statusTip = "Pause Download" , triggered = self.pauseButtonPressed) downloadMenu.addAction(self.pauseAction) self.stopAction = QAction(QIcon(icons + 'stop') , 'Stop Download' , self , shortcut = "Ctrl+S" , statusTip = "Stop/Cancel Download" , triggered = self.stopButtonPressed) downloadMenu.addAction(self.stopAction) self.removeAction = QAction(QIcon(icons + 'trash') , 'Remove Download' , self , shortcut = "Ctrl+D" , statusTip = "Remove Download" , triggered = self.removeButtonPressed) downloadMenu.addAction(self.removeAction) self.propertiesAction = QAction(QIcon(icons + 'setting') , 'Properties' , self , shortcut = "Ctrl+P" , statusTip = "Properties" , triggered = self.propertiesButtonPressed ) downloadMenu.addAction(self.propertiesAction) self.progressAction = QAction(QIcon(icons + 'window') , 'Progress' , self , shortcut = "Ctrl+Z" , statusTip = "Progress" , triggered = self.progressButtonPressed ) downloadMenu.addAction(self.progressAction) self.exitAction = QAction(QIcon(icons + 'exit') , 'Exit' , self , shortcut = "Ctrl+Q" , statusTip = "Exit" , triggered = self.close) fileMenu.addAction(self.exitAction) self.preferencesAction = QAction(QIcon(icons + 'preferences') , 'Preferences' , self , statusTip = 'Preferences' , triggered = self.openPreferences) editMenu.addAction(self.preferencesAction) self.aboutAction = QAction(QIcon(icons + 'about') , 'About' , self , statusTip = 'About' , triggered = self.openAbout) helpMenu.addAction(self.aboutAction) for i in self.addlinkAction,self.resumeAction, self.pauseAction , self.stopAction, self.removeAction , self.propertiesAction, self.progressAction , self.exitAction : self.toolBar.addAction(i) self.toolBar.insertSeparator(self.addlinkAction) self.toolBar.insertSeparator(self.resumeAction) self.toolBar.insertSeparator(self.removeAction) self.toolBar.insertSeparator(self.exitAction) self.toolBar.addSeparator()
def __init__(self,my_server): QWidget.__init__(self) self.myserver=my_server self.win_list=windows() self.win_list.load() self.win_list.set_window(self,"scan_window") self.setWindowTitle(_("Parameter scan - gpvdm")) self.setWindowIcon(QIcon(os.path.join(get_image_file_path(),"scan.png"))) self.rod=[] if os.path.isfile("scan_window.inp"): f = open("scan_window.inp") lines = f.readlines() f.close() path=lines[0].strip() if path.startswith(os.getcwd()): self.sim_dir=path else: self.sim_dir=os.getcwd() else: self.sim_dir=os.getcwd() self.main_vbox = QVBoxLayout() menubar = QMenuBar() file_menu = menubar.addMenu('&File') self.menu_change_dir=file_menu.addAction(_("Change dir")) self.menu_change_dir.triggered.connect(self.callback_close) self.menu_close=file_menu.addAction(_("Close")) self.menu_close.triggered.connect(self.callback_close) self.menu_simulation=menubar.addMenu(_("Simulations")) self.menu_new=self.menu_simulation.addAction(_("&New")) self.menu_new.triggered.connect(self.callback_add_page) self.menu_delete=self.menu_simulation.addAction(_("&Delete simulation")) self.menu_delete.triggered.connect(self.callback_delete_page) self.menu_rename=self.menu_simulation.addAction(_("&Rename simulation")) self.menu_rename.triggered.connect(self.callback_rename_page) self.menu_copy=self.menu_simulation.addAction(_("&Clone simulation")) self.menu_copy.triggered.connect(self.callback_copy_page) self.menu_simulation.addSeparator() self.menu_run=self.menu_simulation.addAction(_("&Run simulation")) self.menu_run.triggered.connect(self.callback_run_simulation) self.menu_advanced=menubar.addMenu(_("Advanced")) self.menu_plot_fits=self.menu_advanced.addAction(_("&Plot fits")) self.menu_plot_fits.triggered.connect(self.callback_plot_fits) self.menu_run_nested=self.menu_advanced.addAction(_("&Run nested simulation")) self.menu_run_nested.triggered.connect(self.callback_nested_simulation) self.menu_run_nested=self.menu_advanced.addAction(_("&Run simulation no generation")) self.menu_run_nested.triggered.connect(self.callback_run_simulation_nogen) self.menu_run_nested=self.menu_advanced.addAction(_("&Run simulation no generation")) self.menu_run_nested.triggered.connect(self.callback_run_simulation_nogen) self.menu_run_single_fit=self.menu_advanced.addAction(_("&Run single fit")) self.menu_run_single_fit.triggered.connect(self.callback_run_single_fit) self.menu_clean_simulation=self.menu_advanced.addAction(_("&Clean simulation")) self.menu_clean_simulation.triggered.connect(self.callback_clean_simulation) self.menu_clean_unconverged_simulation=self.menu_advanced.addAction(_("&Clean unconverged simulation")) self.menu_clean_unconverged_simulation.triggered.connect(self.callback_clean_unconverged_simulation) self.menu_clean_simulation_output=self.menu_advanced.addAction(_("&Clean simulation output")) self.menu_clean_simulation_output.triggered.connect(self.callback_clean_simulation_output) self.menu_clean_simulation_output=self.menu_advanced.addAction(_("&Clean simulation output")) self.menu_clean_simulation_output.triggered.connect(self.callback_clean_simulation_output) self.menu_advanced.addSeparator() self.menu_push_to_hpc=self.menu_advanced.addAction(_("&Push unconverged to hpc")) self.menu_push_to_hpc.triggered.connect(self.callback_push_unconverged_to_hpc) self.menu_help=menubar.addMenu(_("Help")) self.menu_help_help=self.menu_help.addAction(_("Help")) self.menu_help_help.triggered.connect(self.callback_help) self.main_vbox.addWidget(menubar) toolbar=QToolBar() toolbar.setIconSize(QSize(48, 48)) self.tb_new = QAction(QIcon(os.path.join(get_image_file_path(),"new.png")), _("New simulation"), self) self.tb_new.triggered.connect(self.callback_add_page) toolbar.addAction(self.tb_new) self.tb_delete = QAction(QIcon(os.path.join(get_image_file_path(),"delete.png")), _("Delete simulation"), self) self.tb_delete.triggered.connect(self.callback_delete_page) toolbar.addAction(self.tb_delete) self.tb_clone = QAction(QIcon(os.path.join(get_image_file_path(),"clone.png")), _("Clone simulation"), self) self.tb_clone.triggered.connect(self.callback_copy_page) toolbar.addAction(self.tb_clone) self.tb_rename = QAction(QIcon(os.path.join(get_image_file_path(),"rename.png")), _("Rename simulation"), self) self.tb_rename.triggered.connect(self.callback_rename_page) toolbar.addAction(self.tb_rename) self.tb_run_all = QAction(QIcon(os.path.join(get_image_file_path(),"32_forward2.png")), _("Run all simulations"), self) self.tb_run_all.triggered.connect(self.callback_run_all_simulations) toolbar.addAction(self.tb_run_all) spacer = QWidget() spacer.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) toolbar.addWidget(spacer) self.help = QAction(QIcon(os.path.join(get_image_file_path(),"help.png")), 'Hide', self) self.help.setStatusTip(_("Close")) self.help.triggered.connect(self.callback_help) toolbar.addAction(self.help) self.main_vbox.addWidget(toolbar) self.notebook = QTabWidget() self.notebook.setTabBar(QHTabBar()) self.notebook.setTabPosition(QTabWidget.West) self.notebook.setMovable(True) self.main_vbox.addWidget(self.notebook) self.status_bar=QStatusBar() self.main_vbox.addWidget(self.status_bar) self.load_tabs() self.setLayout(self.main_vbox)
class Dialog(QDialog): NumGridRows = 3 NumButtons = 4 def __init__(self): super(Dialog, self).__init__() self.createMenu() self.createHorizontalGroupBox() self.createGridGroupBox() self.createFormGroupBox() bigEditor = QTextEdit() bigEditor.setPlainText("This widget takes up all the remaining space " "in the top-level layout.") buttonBox = QDialogButtonBox( QDialogButtonBox.Ok | QDialogButtonBox.Cancel) buttonBox.accepted.connect(self.accept) buttonBox.rejected.connect(self.reject) mainLayout = QVBoxLayout() mainLayout.setMenuBar(self.menuBar) mainLayout.addWidget(self.horizontalGroupBox) mainLayout.addWidget(self.gridGroupBox) mainLayout.addWidget(self.formGroupBox) mainLayout.addWidget(bigEditor) mainLayout.addWidget(buttonBox) self.setLayout(mainLayout) self.setWindowTitle("Basic Layouts") def createMenu(self): self.menuBar = QMenuBar() self.fileMenu = QMenu("&File", self) self.exitAction = self.fileMenu.addAction("E&xit") self.menuBar.addMenu(self.fileMenu) self.exitAction.triggered.connect(self.accept) def createHorizontalGroupBox(self): self.horizontalGroupBox = QGroupBox("Horizontal layout") layout = QHBoxLayout() for i in range(Dialog.NumButtons): button = QPushButton("Button %d" % (i + 1)) layout.addWidget(button) self.horizontalGroupBox.setLayout(layout) def createGridGroupBox(self): self.gridGroupBox = QGroupBox("Grid layout") layout = QGridLayout() for i in range(Dialog.NumGridRows): label = QLabel("Line %d:" % (i + 1)) lineEdit = QLineEdit() layout.addWidget(label, i + 1, 0) layout.addWidget(lineEdit, i + 1, 1) self.smallEditor = QTextEdit() self.smallEditor.setPlainText("This widget takes up about two thirds " "of the grid layout.") layout.addWidget(self.smallEditor, 0, 2, 4, 1) layout.setColumnStretch(1, 10) layout.setColumnStretch(2, 20) self.gridGroupBox.setLayout(layout) def createFormGroupBox(self): self.formGroupBox = QGroupBox("Form layout") layout = QFormLayout() layout.addRow(QLabel("Line 1:"), QLineEdit()) layout.addRow(QLabel("Line 2, long text:"), QComboBox()) layout.addRow(QLabel("Line 3:"), QSpinBox()) self.formGroupBox.setLayout(layout)
class ViewSourceDialog(QMainWindow): closed = pyqtSignal(QObject) def __init__(self, parent=None, title="Source"): super(ViewSourceDialog, self).__init__() self.setParent(parent) self.menuBar = QMenuBar(self) self.menuBar.setStyleSheet("""QMenuBar { background: transparent; border: 0; } QMenuBar::item { background: transparent; color: palette(window-text); } QMenuBar::item:pressed { background: palette(highlight); color: palette(highlighted-text); }""") self.setMenuBar(self.menuBar) self.text = "" self.findFlag = None self.fileMenu = QMenu(tr("&File"), self.menuBar) self.menuBar.addMenu(self.fileMenu) self.saveAsAction = QAction(tr("&Save As..."), self) self.saveAsAction.setShortcut("Ctrl+S") self.saveAsAction.triggered.connect(self.saveAs) self.addAction(self.saveAsAction) self.fileMenu.addAction(self.saveAsAction) self.viewMenu = QMenu(tr("&View"), self.menuBar) self.menuBar.addMenu(self.viewMenu) self.findAction = QAction(tr("&Find..."), self) self.findAction.setShortcut("Ctrl+F") self.findAction.triggered.connect(self.find) self.addAction(self.findAction) self.viewMenu.addAction(self.findAction) self.findNextAction = QAction(tr("Find Ne&xt"), self) self.findNextAction.setShortcut("Ctrl+G") self.findNextAction.triggered.connect(self.findNext) self.addAction(self.findNextAction) self.viewMenu.addAction(self.findNextAction) self.findPreviousAction = QAction(tr("Find Pre&vious"), self) self.findPreviousAction.setShortcut("Ctrl+Shift+G") self.findPreviousAction.triggered.connect(self.findPrevious) self.addAction(self.findPreviousAction) self.viewMenu.addAction(self.findPreviousAction) self.sourceView = SourceView(self) self.sourceView.setReadOnly(True) self.sourceView.setFontFamily("monospace") self.setCentralWidget(self.sourceView) closeWindowAction = QAction(self) closeWindowAction.setShortcut("Ctrl+W") closeWindowAction.triggered.connect(self.close) self.addAction(closeWindowAction) self.setWindowTitle(title) self.resize(640, 480) def closeEvent(self, ev): super(ViewSourceDialog, self).closeEvent(ev) self.deleteLater() def saveAs(self): fname = QFileDialog.getSaveFileName(None, tr("Save As..."), self.windowTitle() + ".txt", tr("Text files (*.txt)")) if type(fname) is tuple: fname = fname[0] if fname: g = str(self.sourceView.toPlainText()) f = open(fname, "w") f.write(g) f.close() def find(self): find = QInputDialog.getText(self, tr("Find"), tr("Search for:"), QLineEdit.Normal, self.text) if find[1]: self.text = find[0] else: self.text = "" if self.findFlag: self.sourceView.find(self.text, self.findFlag) else: self.sourceView.find(self.text) def findNext(self, findFlag=None): if not self.text: self.find() else: self.findFlag = findFlag if self.findFlag: self.sourceView.find(self.text, self.findFlag) else: self.sourceView.find(self.text) def findPrevious(self): self.findNext(QTextDocument.FindBackward) def setFindFlag(self): if self.findReverseAction.isChecked(): self.findFlag = QTextDocument.FindBackward else: self.findFlag = None def setPlainText(self, *args, **kwargs): self.sourceView.setPlainText(*args, **kwargs) def doNothing(self): pass def closeEvent(self, ev): self.closed.emit(self) self.deleteLater() ev.accept()
def __init__(self): QWidget.__init__(self) self.setMinimumSize(1200, 700) self.win_list=windows() self.win_list.load() self.win_list.set_window(self,"fxexperiments_window") self.main_vbox = QVBoxLayout() menubar = QMenuBar() file_menu = menubar.addMenu('&File') self.menu_close=file_menu.addAction(_("Close")) self.menu_close.triggered.connect(self.callback_close) self.menu_experiment=menubar.addMenu(_("Experiments")) self.menu_experiment_new=self.menu_experiment.addAction(_("&New")) self.menu_experiment_new.triggered.connect(self.callback_add_page) self.menu_experiment_delete=self.menu_experiment.addAction(_("&Delete experiment")) self.menu_experiment_delete.triggered.connect(self.callback_delete_page) self.menu_experiment_rename=self.menu_experiment.addAction(_("&Rename experiment")) self.menu_experiment_rename.triggered.connect(self.callback_rename_page) self.menu_experiment_clone=self.menu_experiment.addAction(_("&Clone experiment")) self.menu_experiment_clone.triggered.connect(self.callback_copy_page) self.menu_help=menubar.addMenu(_("Help")) self.menu_help_help=self.menu_help.addAction(_("Help")) self.menu_help_help.triggered.connect(self.callback_help) self.main_vbox.addWidget(menubar) self.setWindowTitle(_("Frequency domain experiment editor - gpvdm")) self.setWindowIcon(QIcon(os.path.join(get_image_file_path(),"spectrum.png"))) toolbar=QToolBar() toolbar.setIconSize(QSize(48, 48)) self.new = QAction(QIcon(os.path.join(get_image_file_path(),"new.png")), _("New experiment"), self) self.new.triggered.connect(self.callback_add_page) toolbar.addAction(self.new) self.new = QAction(QIcon(os.path.join(get_image_file_path(),"delete.png")), _("Delete experiment"), self) self.new.triggered.connect(self.callback_delete_page) toolbar.addAction(self.new) self.clone = QAction(QIcon(os.path.join(get_image_file_path(),"clone.png")), _("Clone experiment"), self) self.clone.triggered.connect(self.callback_copy_page) toolbar.addAction(self.clone) self.clone = QAction(QIcon(os.path.join(get_image_file_path(),"rename.png")), _("Rename experiment"), self) self.clone.triggered.connect(self.callback_rename_page) toolbar.addAction(self.clone) spacer = QWidget() spacer.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) toolbar.addWidget(spacer) self.help = QAction(QIcon(os.path.join(get_image_file_path(),"help.png")), 'Hide', self) self.help.setStatusTip(_("Close")) self.help.triggered.connect(self.callback_help) toolbar.addAction(self.help) self.main_vbox.addWidget(toolbar) self.notebook = QTabWidget() self.notebook.setTabBar(QHTabBar()) self.notebook.setTabPosition(QTabWidget.West) self.notebook.setMovable(True) self.load_tabs() self.main_vbox.addWidget(self.notebook) self.status_bar=QStatusBar() self.main_vbox.addWidget(self.status_bar) self.setLayout(self.main_vbox)
def __init__(self): QWidget.__init__(self) self.win_list=windows() self.win_list.load() self.win_list.set_window(self,"laser_window") self.main_vbox = QVBoxLayout() menubar = QMenuBar() file_menu = menubar.addMenu('&File') self.menu_close=file_menu.addAction(_("Close")) self.menu_close.triggered.connect(self.callback_close) self.menu_lasers=menubar.addMenu(_("Lasers")) self.menu_lasers_new=self.menu_lasers.addAction(_("&New")) self.menu_lasers_new.triggered.connect(self.callback_add_page) self.menu_lasers_delete=self.menu_lasers.addAction(_("&Delete laser")) self.menu_lasers_delete.triggered.connect(self.callback_delete_page) self.menu_lasers_rename=self.menu_lasers.addAction(_("&Rename laser")) self.menu_lasers_rename.triggered.connect(self.callback_rename_page) self.menu_lasers_rename=self.menu_lasers.addAction(_("&Rename laser")) self.menu_lasers_rename.triggered.connect(self.callback_rename_page) self.menu_lasers_clone=self.menu_lasers.addAction(_("&Clone laser")) self.menu_lasers_clone.triggered.connect(self.callback_copy_page) self.menu_help=menubar.addMenu(_("Help")) self.menu_help_help=self.menu_help.addAction(_("Help")) self.menu_help_help.triggered.connect(self.callback_help) self.main_vbox.addWidget(menubar) self.setFixedSize(900, 500) self.setWindowTitle(_("Laser configuration window - gpvdm")) self.setWindowIcon(QIcon(os.path.join(get_image_file_path(),"lasers.png"))) toolbar=QToolBar() toolbar.setIconSize(QSize(48, 48)) self.new = QAction(QIcon(os.path.join(get_image_file_path(),"new.png")), _("New laser"), self) self.new.triggered.connect(self.callback_add_page) toolbar.addAction(self.new) self.new = QAction(QIcon(os.path.join(get_image_file_path(),"delete.png")), _("Delete laser"), self) self.new.triggered.connect(self.callback_delete_page) toolbar.addAction(self.new) self.clone = QAction(QIcon(os.path.join(get_image_file_path(),"clone.png")), _("Clone laser"), self) self.clone.triggered.connect(self.callback_copy_page) toolbar.addAction(self.clone) self.clone = QAction(QIcon(os.path.join(get_image_file_path(),"rename.png")), _("Rename laser"), self) self.clone.triggered.connect(self.callback_rename_page) toolbar.addAction(self.clone) spacer = QWidget() spacer.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) toolbar.addWidget(spacer) self.help = QAction(QIcon(os.path.join(get_image_file_path(),"help.png")), 'Hide', self) self.help.setStatusTip(_("Close")) self.help.triggered.connect(self.callback_help) toolbar.addAction(self.help) self.main_vbox.addWidget(toolbar) self.notebook = QTabWidget() self.notebook.setMovable(True) self.load_tabs() self.main_vbox.addWidget(self.notebook) self.status_bar=QStatusBar() self.main_vbox.addWidget(self.status_bar) self.setLayout(self.main_vbox)
#!/usr/bin/env python # -*- coding:utf-8 -*- __author__ = 'tim' from PyQt5.QtWidgets import QApplication,QMenuBar import sys app=QApplication(sys.argv) menubar=QMenuBar() #QMenubar是横向菜单栏 files=menubar.addMenu('File') #添加菜单 menubar.addMenu('Edit') menubar.addMenu('View') menubar.addMenu('Code') menubar.addMenu('Run') menubar.addMenu('Tools') files.addAction('Open') #添加菜单下子菜单 project=files.addAction('New Project') Exit=files.addAction('Exit') files.addActions([project,Exit]) ##添加1组子菜单 menubar.show() sys.exit(app.exec_())
class Dialog(QDialog): NumGridRows = 3 NumButtons = 4 ## #Window Initialization ## def __init__(self): super(Dialog, self).__init__() self.createMenu() self.widget_register_url() self.widget_download() self.thread_download = threading.Thread( group=None, target=self.run_downloader, name=None, args=(), kwargs={}, daemon=True ) self.running = False bigEditor = QTextEdit() bigEditor.setPlainText("This widget takes up all the remaining space " "in the top-level layout.") buttonBox = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel) buttonBox.accepted.connect(self.accept) buttonBox.rejected.connect(self.reject) mainLayout = QVBoxLayout() mainLayout.setMenuBar(self.menuBar) mainLayout.addWidget(self.form_register_url) mainLayout.addWidget(self.form_download_urls) self.setLayout(mainLayout) self.setWindowTitle("Bamboodl") def createMenu(self): self.menuBar = QMenuBar() self.fileMenu = QMenu("&File", self) self.exitAction = self.fileMenu.addAction("E&xit") self.exitAction.setShortcut('Ctrl+Q') self.exitAction.setStatusTip('Exit application') #self.exitAction.triggered.connect(qApp.quit) self.menuBar.addMenu(self.fileMenu) self.exitAction.triggered.connect(self.accept) def createButton(self, text, member): button = QPushButton(text) button.clicked.connect(member) return button ## #Registering a new URL ## def set_label_text_register(self, new_text): self.label_new_url_debug.setText(new_text) def click_process_new_url(self): global subscribe, paths, key_regex, key_reg_replace line = self.text_input_new_url.text() if line.isspace(): self.set_label_text_register("'URL' space is blank, enter a url!") else: json_test="" domain = extract_root_domain_from_url(line.replace('\n','')) if domain in key_regex: myregex = re.compile(key_regex[domain]) line_parsed = myregex.sub(key_reg_replace[domain], line) try: json_test = json.loads(line_parsed) except Exception as e: debug("\nInvalid URL:" + line.replace('\n',''), critical=True) #raise e #print("WHOOPS there was an error!") return temp_string = add_json_to_subscribe(json_test) self.text_input_new_url.clear() #If the downloader is running, add the subscription just created to the list for the downloaders to grab if self.running: print("ADDING A THING WHILE RUNNING") watch_subscription_or_dont(json_test) #Update the debug field if there's feedback, if temp_string != None: self.set_label_text_register(temp_string) #Otherwise, blank it. else: self.set_label_text_register("Enter URLs here and press 'Register' to add them to your subscriptions.") else: if domain == None: self.set_label_text_register("Invalid URL") else: self.set_label_text_register("No handler for: " + domain) def widget_register_url(self): self.form_register_url = QGroupBox("Register new URL") layout = QFormLayout() self.text_input_new_url = QLineEdit() self.button_register_url = self.createButton("Register", self.click_process_new_url) layout.addRow(self.button_register_url, self.text_input_new_url) self.label_new_url_debug = QLabel("Enter URLs here and press 'Register' to add them to your subscriptions.") layout.addRow(self.label_new_url_debug) self.form_register_url.setLayout(layout) ## #Running Bamboodl Update ## def run_downloader(self): self.running = True #2 Spawn Fetch threads for everything, run through regular link list by date, seeing if wait time has been reached, and if so spawn a Fetch thread self.set_label_text_download("Preparing to download. . .") check_everything() spawn_downloaders() #3 Wait for those threads to join again~ self.append_label_text_download("Downloading. . .") join_downloaders() self.append_label_text_download("Done downloading.") self.running = False def set_label_text_download(self, new_text): self.label_download_debug.setText(new_text) def append_label_text_download(self, new_text): self.label_download_debug.setText(self.label_download_debug.text() + '\n' + new_text) def click_process_download(self): if self.running: pass else: self.thread_download = threading.Thread( group=None, target=self.run_downloader, name=None, args=(), kwargs={}, daemon=True ) self.thread_download.start() def widget_download(self): self.form_download_urls = QGroupBox("Download subscribed threads") layout = QFormLayout() self.button_download = self.createButton("Normal Update", self.click_process_download) layout.addRow(self.button_download) self.label_download_debug = QLabel("Press the button above to download updates to the threads you've subscribed to.") layout.addRow(self.label_download_debug) self.form_download_urls.setLayout(layout)
class CellularAutomatonQt(QWidget): def __init__(self, cellular_automaton): super().__init__() self.speed = DEFAULT_SIMULATION_SPEED self.cell_size = CELL_SIZE self.cellular_automaton = cellular_automaton self.num_of_cells_x = self.cellular_automaton.size_x self.num_of_cells_y = self.cellular_automaton.size_y self.run = False self.setWindowTitle('Cellular automaton') self.setToolTip('Select cell') self.start_btn = QPushButton('Start', self) self.start_btn.setToolTip('Start simulation') self.clear_btn = QPushButton('Clear', self) self.clear_btn.setToolTip('Clear board') self.start_btn.clicked.connect(self.toggle) self.clear_btn.clicked.connect(self.clean) self.timer = QTimer(self) self.timer.timeout.connect(self.paint_update) self.slider = QSlider(Qt.Horizontal, self) self.slider.setMinimum(MIN_SIMULATION_SPEED) self.slider.setMaximum(MAX_SIMULATION_SPEED) self.slider.setValue(DEFAULT_SIMULATION_SPEED) self.slider.setToolTip('Speed of simulation') self.slider.valueChanged.connect(self.set_value) btn_layout = QHBoxLayout() btn_layout.addWidget(self.start_btn) btn_layout.addWidget(self.clear_btn) layout = QVBoxLayout() layout.setAlignment(Qt.AlignBottom) layout.addLayout(btn_layout, Qt.AlignCenter) layout.addWidget(self.slider, Qt.AlignCenter) self.setLayout(layout) self.menu_bar = QMenuBar(self) self.add_menu_bar() self.margin_left = MARGIN self.margin_top = MARGIN self.resize(WINDOW_X_SIZE, WINDOW_Y_SIZE) self.setMinimumSize(WINDOW_X_SIZE, WINDOW_Y_SIZE) self.resizeEvent = self.on_resize def add_menu_bar(self): exit_menu = self.menu_bar.addMenu('File') conway_action = QAction('Conway Life Game', self) cf = partial(self.set_automaton, ConwayLifeOutflow(NUM_OF_CELLS_X, NUM_OF_CELLS_Y)) conway_action.triggered.connect(cf) exit_menu.addAction(conway_action) sand_action = QAction('Sand', self) sf = partial(self.set_automaton, Sand(NUM_OF_CELLS_X, NUM_OF_CELLS_Y)) sand_action.triggered.connect(sf) exit_menu.addAction(sand_action) exit_action = QAction('Exit', self) exit_action.triggered.connect(self.close) exit_menu.addAction(exit_action) def set_automaton(self, cellular_automaton): self.cellular_automaton = cellular_automaton self.num_of_cells_x = self.cellular_automaton.size_x self.num_of_cells_y = self.cellular_automaton.size_y self.repaint() def on_resize(self, event): """Resize grid""" width, height = self.width(), self.height() new_x_cell_size = (width - MARGIN*2) // self.num_of_cells_x new_y_cell_size = (height - MARGIN*2) // self.num_of_cells_y self.cell_size = min(new_x_cell_size, new_y_cell_size) self.margin_left = (width - self.cell_size*self.num_of_cells_x) // 2 self.margin_top = (height - self.cell_size*self.num_of_cells_y) // 2 self.repaint() def set_value(self): """Set slider value""" self.speed = self.slider.value() if self.run: self.timer.stop() self.timer.start(self.speed) def toggle(self): """Start simulation""" if not self.run: self.run = True self.start_btn.setToolTip('End simulation') self.start_btn.setText('End') self.timer.start(self.speed) else: self.run = False self.start_btn.setToolTip('Start') self.start_btn.setText('Start simulation') self.timer.stop() def clean(self): self.toggle() self.cellular_automaton.clean() self.repaint() def mousePressEvent(self, event): x, y = self._convert_coordinates(event.x(), event.y()) self._update_cell(x, y) def mouseMoveEvent(self, event): x, y = self._convert_coordinates(event.x(), event.y()) self._update_cell(x, y) def _convert_coordinates(self, x, y): x = (x - self.margin_left) // self.cell_size y = (y - self.margin_top) // self.cell_size return int(x), int(y) def _update_cell(self, x, y): if 0 <= x < self.num_of_cells_x and 0 <= y < self.num_of_cells_y: self.cellular_automaton.update_cell(x, y) self.repaint() def paint_cell(self, i, j, color, painter): i_paint_cord = i*self.cell_size + self.margin_left j_paint_cord = j*self.cell_size + self.margin_top painter.fillRect( i_paint_cord, j_paint_cord, self.cell_size, self.cell_size, QtGui.QBrush(QtGui.QColor(color))) def paintEvent(self, event): painter = QtGui.QPainter() painter.begin(self) painter.fillRect(event.rect(), QtGui.QBrush(Qt.white)) painter.setRenderHint(QtGui.QPainter.Antialiasing) cells = product(range(self.num_of_cells_x), range(self.num_of_cells_y)) for i, j in cells: to_paint, color = self.cellular_automaton.check_cell(j, i) if to_paint: self.paint_cell(i, j, color, painter) self._draw_lines(painter) painter.end() def _draw_lines(self, painter, line_width=1, line_color=Qt.gray, line_style=Qt.SolidLine): painter.setPen(QtGui.QPen(QtGui.QBrush(line_color), 1, line_style)) start_x, start_y = self.margin_left, self.margin_top stop_x = self.num_of_cells_x*self.cell_size + start_x stop_y = self.num_of_cells_y*self.cell_size + start_y for i in range(start_y, stop_y + self.cell_size, self.cell_size): painter.drawLine(start_x, i, stop_x, i) for i in range(start_x, stop_x + self.cell_size, self.cell_size): painter.drawLine(i, start_y, i, stop_y) def paint_update(self): self.cellular_automaton.update_table() self.repaint()
class MainWindow(QMainWindow): def __init__(self, settings): super().__init__() # Save the settings object for now and shutdown time. self.settings = settings # Initialize extras and dicts paths first, as other modules use them paths.initialize(settings) # Initialize our font db fonts.initialize(settings) # Set our font, which will propogate to our child widgets. fonts.notify_me(self._font_change) # ask for a signal self._font_change(False) # fake a signal now # Initialize the dictionary apparatus dictionaries.initialize(settings) # Initialize the color choices colors.initialize(settings) # Initialize the sequence number for opened files self.book_number = 0 # Initialize the path to the last-opened file, used to # start file-open dialogs. self.last_open_path = '.' # Initialize our dict of active panels self.panel_dict = PANEL_DICT.copy() # Initialize our dict of open documents {seqno:Book} self.open_books = {} self.focus_book = None # seqno of book in focus, see _focus_me # Initialize the list of recent files self.recent_files = [] # Create the main window and set up the menus. self._uic() # Initialize the set of files actually open when we shut down. last_session = self._read_flist('mainwindow/open_files') if len(last_session) : # there were some files open if len(last_session) == 1 : msg = _TR('Start-up dialog', 'One book was open at the end of the last session.') else: msg = _TR('Start-up dialog', '%n books were open at the end of the last session.', n=len(last_session) ) info = _TR("Start-up dialog", "Click OK to re-open all") if utilities.ok_cancel_msg( msg, info) : for file_path in last_session : ftbs = utilities.path_to_stream(file_path) if ftbs : self._open(ftbs) if 0 == len(self.open_books) : # We did not re-open any books, either because there were # none, or the user said No, or perhaps they were not found. self._new() # open one, new, book. # -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= # Slot to receive the currentChanged signal from the editview tabset. # Look through self.open_books and find the one whose edit widget is # now current, and do a focus_me for it. def _editview_change(self, index): if index > -1 : eview = self.editview_tabset.widget(index) for (seqno, book) in self.open_books.items() : if eview == book.get_edit_view() : self.focus_me(seqno) return mainwindow_logger.error('cannot relate editview tab index to book') # -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= # Make a selected book the focus of all panels. This is called explicitly # when a book is first created, and when the editview tabset changes the # current selection. It is called also when an editview gets a focus-in # event. # Display that Book's various "-view" objects in panels, in the order # that the user left them and with the same active panel as before. Note # that a book (editview) can get a focus-in event when it was already the # focus in this sense, for example if this app was hidden and then # brought to the front. So be prepared for redundant calls. def focus_me(self, book_index): outgoing = self.focus_book if book_index == outgoing : return # redundant call mainwindow_logger.debug( 'focusing {0} = {1}'.format(book_index,self.open_books[book_index].get_book_name()) ) self.focus_book = book_index # Record the user's arrangement of panels for the outgoing book, # as a list of tuples ('tabname', widget) in correct sequence. if outgoing is not None : # false first time and after File>Close out_panel_dict = self.open_books[outgoing].panel_dict widg_list = [] for ix in range( self.panel_tabset.count() ): widg_list.append ( (self.panel_tabset.tabText(ix), self.panel_tabset.widget(ix)) ) out_panel_dict['tab_list'] = widg_list out_panel_dict['current'] = self.panel_tabset.currentIndex() # Change all the panels to the widgets, in the sequence, of the new book in_panel_dict = self.open_books[book_index].panel_dict widg_list = in_panel_dict['tab_list'] self.panel_tabset.clear() for ix in range( len(widg_list) ): (tab_text, widget) = widg_list[ix] self.panel_tabset.insertTab(ix, widget, tab_text) self.panel_tabset.setCurrentIndex(in_panel_dict['current']) self.editview_tabset.setCurrentIndex( self.editview_tabset.indexOf( self.open_books[book_index].get_edit_view() ) ) # -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= # Called by the current book to make a particular tab the visible one, # e.g. to make the Find visible on a ^F. The argument is a widget # that should occupy one of the current tabs. Ask the tabset for its # index, and if it is found, make that the current index. (If it is # not found, log it and do nothing.) def make_tab_visible(self, tabwidg): ix = self.panel_tabset.indexOf(tabwidg) if ix >= 0 : # widget exists in this tabset self.panel_tabset.setCurrentIndex(ix) return mainwindow_logger.error('Request to show nonexistent widget') # -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= # Implement File>New: # Create a Book object # Call its new_empty() method, # Add it to the open_books dict keyed by its sequence number, # Display its text editor in a tab with the document name, and # Give it the focus. def _new(self): seq = self.book_number self.book_number += 1 new_book = book.Book( seq, self ) new_book.new_empty() self.open_books[seq] = new_book index = self.editview_tabset.addTab( new_book.get_edit_view(), new_book.get_book_name() ) self.editview_tabset.setTabToolTip(index, _TR('Tooltip of edit of new unsaved file', 'this file has not been saved') ) self.focus_me(seq) # -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= # Quick check to see if a file path is already open. Called from _open # and from _build_recent (menu). Returned value is the sequence number # of the open book, or None. def _is_already_open(self, path): for (seq, book_object) in self.open_books.items(): if path == book_object.get_book_full_path() : return seq return None # -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= # Implement File>Open. Dialog with the user (file dialog starts with # last-used book path). Result is None or a FileBasedTextStream that we # pass to _open(). def _file_open(self) : fbts = utilities.ask_existing_file( _TR( 'File:Open dialog','Select a book file to open'), parent=self, starting_path=self.last_open_path) if fbts : # yes a readable file was chosen. self._open( fbts ) # -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= # Open a file, given the document as a FileBasedTextStream # * If file opened is fname.meta, look for a file named fname; if it # exists open it instead, e.g. given foo.txt.meta, open foo.txt. # If it doesn't exist, tell the user and exit. # * If a file of the same name and path is already open, just focus # it and exit. # * Determine if there is a .meta file, a .bin file, or neither # * Create a metadata input stream if possible # * If no .meta, look for good_words and bad_words # * If the only open book is an "Untitled-n" and # it is unmodified, delete it. # * Call Book.old_book() or .new_book() as appropriate # * Add this book's editview to the edit tabset # * Give this book the focus. def _open(self, fbts): # look for opening a .meta file if 'meta' == fbts.suffix(): fb2 = utilities.file_less_suffix(fbts) if fb2 is None : m1 = _TR('File:Open','Cannot open a .meta file alone') m2 = _TR('File:Open','There is no book file matching ', 'filename follows this') + fbts.filename() utilities.warning_msg(m1, m2) return # we see foo.txt with foo.txt.meta, silently open it fbts = fb2 # look for already-open file seq = self._is_already_open(fbts.fullpath()) if seq is not None : self.focus_me(seq) return # start collecting auxiliary streams gw_stream = None bw_stream = None gg_stream = None # open the metadata stream, which is always UTF-8 meta_stream = utilities.related_suffix(fbts, 'meta', encoding=C.ENCODING_UTF) if meta_stream is None : # opening book without .meta; look for .bin which is always LTN1 bin_stream = utilities.related_suffix(fbts,'bin',encoding=C.ENCODING_LATIN) if bin_stream : gg_stream = metadata.translate_bin(bin_stream,fbts) # Look for good_words.txt, bad_words.txt. gw_stream = utilities.related_file( fbts, 'good_words*.*' ) bw_stream = utilities.related_file( fbts, 'bad_words*.*' ) seq = self.book_number # If the only open book is the new one created at startup or when all # books are closed (which will have key 0), and it has not been # modified, get rid of it. if len(self.open_books) == 1 \ and 0 == list(self.open_books.keys())[0] \ and self.open_books[0].get_book_name().startswith('Untitled-') \ and not self.open_books[0].get_save_needed() : self.editview_tabset.clear() self.panel_tabset.clear() self.focus_book = None seq = 0 else: # Some other book open, or user typed into the default New one. self.book_number += 1 # Make the Book object and stow it in our open book dict a_book = book.Book( seq, self ) self.open_books[seq] = a_book if meta_stream : # opening a book we previously saved a_book.old_book( fbts, meta_stream ) else : a_book.new_book( fbts, gg_stream, gw_stream, bw_stream ) index = self.editview_tabset.addTab( a_book.get_edit_view(), a_book.get_book_name()) self.editview_tabset.setTabToolTip(index, a_book.get_book_folder() ) self.focus_me(seq) self.last_open_path = fbts.folderpath() # start for next open or save self._add_to_recent(fbts.fullpath()) # -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= # Save the book that is currently in focus under its present name, if it # is modified. Return True if the save completed, else False. # If the active book is a New one, force a Save-As action instead. def _save(self): active_book = self.open_books[self.focus_book] if active_book.get_save_needed() : if active_book.get_book_name().startswith('Untitled-'): return self._save_as() doc_stream = utilities.path_to_output( active_book.get_book_full_path() ) if doc_stream : # successfully opened for output meta_stream = utilities.related_output(doc_stream,'meta') if not meta_stream: utilities.warning_msg( _TR('File:Save', 'Unable to open metadata file for writing.'), _TR('File:Save', 'Use loglevel=error for details.') ) return False else: utilities.warning_msg( _TR('File:Save', 'Unable to open book file for writing.'), _TR('File:Save', 'Use loglevel=error for details.') ) return False return active_book.save_book(doc_stream, meta_stream) # -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= # Implement Save As. Query the user for a file path and get that as an # output FileBasedTextStream. Call the book to rename itself, which makes # it modified. Change the text in the edit tab to match. Discard the FBTS # and call _save which will make another one. def _save_as(self): active_book = self.open_books[self.focus_book] fbts = utilities.ask_saving_file( _TR('File:Save As dialog', 'Choose a new location and filename for this book' ), self, active_book.get_book_folder() ) if fbts : active_book.rename_book(fbts) self.editview_tabset.setTabText( self.editview_tabset.currentIndex(), fbts.filename() ) self._add_to_recent(fbts.fullpath()) fbts = None # discard that object return self._save() else: return False # -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= # Implement Close. If the active book is modified, ask if it should # be saved. If it is 'Untitled-' that will turn into Save As. def _close(self): target_index = self.focus_book # active edit tab is to close target_book = self.open_books[target_index] if target_book.get_save_needed() : # Compose message of translated parts because _TR does not # allow for incorporating strings, only numbers. msg = _TR('File Close dialog', 'Book file ', 'filename follows here') msg += target_book.get_book_name() msg += _TR('File Close dialog', ' has been modified!', 'filename precedes this') ret = utilities.save_discard_cancel_msg( msg, info = _TR('File Close dialog', 'Save it, Discard changes, or Cancel Closing?') ) if ret is None : # Cancel return if ret : # True==Save self._save() # Now, get rid of the active book in 3 steps, # 1, close the book's tab in the editview tabset. We don't know which # tab it is, because the user can drag tabs around. i = self.editview_tabset.indexOf(target_book.get_edit_view()) # The following causes another tab to be focussed, changing self.focus_book # and saving target_book's tabs in target_book, not that we care. self.editview_tabset.removeTab(i) # 2, remove the book from our dict of open books. del self.open_books[target_index] # 3, if there are any open books remaining, the tab widget has # activated one of them by its rules, which caused a show signal and # entry to _focus_me already. However if there are no remaining books # there was no show signal or focus_me and the closed book's panels # are still in the tabset. if 0 == len(self.open_books) : self.book_number = 0 # restart the sequence self.focus_book = None self._new() # One way or the other, a focus_me has removed all references to # active_book's view panels except those in its PANEL_DICT. So the # following assignment should remove the last reference to the book, # and schedule the book and associated objects for garbage collect. target_book = None # -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= # Implement loading and saving find panel user buttons. Start the search # for files in the active book's folder. User can navigate to extras # if need be. def _find_save(self): target_book = self.open_books[self.focus_book] find_panel = target_book.get_find_panel() stream = utilities.ask_saving_file( _TR('File:Save Find Buttons open dialog', 'Choose file to contain find button definitions'), self, starting_path=target_book.get_book_full_path(), encoding='UTF-8') if stream : # is not None, file is open find_panel.user_button_output(stream) # else user hit cancel, forget it def _find_load(self): target_book = self.open_books[self.focus_book] find_panel = target_book.get_find_panel() stream = utilities.ask_existing_file( _TR('File:Load Find Buttons open dialog', 'Choose a file of find button definitions'), self, starting_path=target_book.get_book_full_path(), encoding='UTF-8') if stream :# is not None, we opened it find_panel.user_button_input(stream) target_book.metadata_modified(True,C.MD_MOD_FLAG) # -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= # Maintain the list of "recent" file paths. The list is kept in usage # order, so if a path is in the list now, delete it and then add it to # the front. Keep it at a max of 9 items by deleting the oldest if # necessary. def _add_to_recent(self, path): if path in self.recent_files : del self.recent_files[self.recent_files.index(path)] self.recent_files.insert(0,path) self.recent_files = self.recent_files[:9] # Upon the aboutToShow signal from the File menu, populate the Recent # submenu with a list of files, but only the ones that are currently # accessible. If one is on a volume (e.g. USB stick) and you unmount the # volume, the path should not appear in the menu until the volume is # mounted again. def _open_recent(self, path): fbts = utilities.path_to_stream(path) if fbts : self._open(fbts) def _build_recent(self): active_files = [] for path in self.recent_files: seq = self._is_already_open(path) if (seq is None) and utilities.file_is_accessible(path) : active_files.append( (utilities.file_split(path),path) ) if 0 == len(active_files): self.recent_menu.setEnabled(False) return self.recent_menu.setEnabled(True) self.recent_menu.clear() i = 1 for ((fname, folder), path) in active_files: act = self.recent_menu.addAction( '{0} {1} {2}'.format(i,fname,folder) ) act.triggered.connect( lambda: self._open_recent(path) ) i += 1 # -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= # User has chosen a different font; if it is the general font, set # that here so it will propogate to our children. def _font_change(self, is_mono): if not is_mono: self.setFont(fonts.get_general()) # -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= # Create the UI contained within this QMainWindow object. This is a lean # main window indeed. We have no toolbar, no status bar, no dock, # nothing. Just a splitter with, on the left, a tabset for editviews, and # on the right, a scrollbar containing a tabset for panels. (Qt Designer # note: it is not possible to build this structure with the Designer. It # will not let you put the scroll area into the splitter.) # # TODO: create a custom QTabWidget using a custom QTabBar to implement # drag-out-of-tabset behavior, and use those here. def _uic(self): # Create the tabset that displays editviews self.editview_tabset = QTabWidget() self.editview_tabset.setMovable(True) # let user move tabs around self.editview_tabset.currentChanged.connect(self._editview_change) # Create the tabset that displays find, notes, help &etc. self.panel_tabset = QTabWidget() self.panel_tabset.setMovable(True) # Create the splitter that contains the above two parts. self.splitter = QSplitter(Qt.Horizontal, self) self.splitter.setChildrenCollapsible(False) # Give just a little margin to the left of the editor self.splitter.setContentsMargins(8,0,0,0) self.splitter.addWidget(self.editview_tabset) self.splitter.addWidget(self.panel_tabset) # Set that splitter as the main window's central (and only) widget self.setCentralWidget(self.splitter) # Populate the panel tabset with empty widgets just so there will # be tabs that _swap can reference. for key in self.panel_dict.keys(): widj = QWidget() self.panel_tabset.addTab(widj,key) self.panel_dict[key] = widj # Size and position ourself based on saved settings. self.move(self.settings.value("mainwindow/position", QPoint(50,50))) self.resize(self.settings.value("mainwindow/size", C.STARTUP_DEFAULT_SIZE)) self.splitter.restoreState( self.settings.value("mainwindow/splitter",C.STARTUP_DEFAULT_SPLITTER) ) # Store a reference to the application menubar. In Mac OS this # is a parentless menubar; other platforms it is the default. if C.PLATFORM_IS_MAC : self.menu_bar = QMenuBar() # parentless menu bar for Mac OS else : self.menu_bar = self.menuBar # refer to the default one set_menu_bar(self.menu_bar) # Create the File menu, located in our menu_bar. self.file_menu = self.menu_bar.addMenu(_TR('Menu name', '&File')) # Populate the File menu with actions. # File:New -> _new() work = self.file_menu.addAction( _TR('File menu command','&New') ) work.setShortcut(QKeySequence.New) work.setToolTip( _TR('File:New tooltip','Create a new, empty document') ) work.triggered.connect(self._new) # File:Open -> _file_open() work = self.file_menu.addAction( _TR('File menu command','&Open') ) work.setShortcut(QKeySequence.Open) work.setToolTip( _TR('File:Open tooltip','Open an existing book') ) work.triggered.connect(self._file_open) # File:Save -> _file_save() work = self.file_menu.addAction( _TR('File menu command', '&Save') ) work.setShortcut(QKeySequence.Save) work.setToolTip( _TR('File:Save tooltip','Save the active book') ) work.triggered.connect(self._save) # Save As -> _file_save_as() work = self.file_menu.addAction( _TR('File menu command', 'Save &As') ) work.setShortcut(QKeySequence.SaveAs) work.setToolTip( _TR('File:Save As tooltip','Save the active book under a new name') ) work.triggered.connect(self._save_as) # Close -> _close() work = self.file_menu.addAction( _TR('File menu command', 'Close') ) work.setShortcut(QKeySequence.Close) work.setToolTip( _TR('File:Close tooltip', 'Close the active book') ) work.triggered.connect(self._close) # Load Find Buttons -> _find_load() work = self.file_menu.addAction( _TR('File menu command', 'Load Find Buttons') ) work.setToolTip( _TR('File:Load Find Buttons tooltip', 'Load a file of definitions for the custom buttons in the Find panel' ) ) work.triggered.connect(self._find_load) # Save Find Buttons -> _find_save() work = self.file_menu.addAction( _TR('File menu command', 'Save Find Buttons') ) work.setToolTip( _TR('File:Save Find Buttons tooltip', 'Save definitions of the custom buttons in the Find panel' ) ) work.triggered.connect(self._find_save) # Open Recent gets a submenu that is added to the File menu. # The aboutToShow signal is connected to our _build_recent slot. self.recent_menu = QMenu( _TR('Sub-menu name', '&Recent Files') ) work = self.file_menu.addMenu( self.recent_menu ) work.setToolTip( _TR('File:Recent tooltip', 'List of recently-used files to open') ) self.file_menu.aboutToShow.connect(self._build_recent) # divider if not Mac if not C.PLATFORM_IS_MAC: self.file_menu.addSeparator() # TODO Preferences with the menu role that on mac, moves to the app menu # Quit with the menu role that moves it to the app menu work = QAction( _TR('Quit command','&Quit'), self ) work.setMenuRole(QAction.QuitRole) work.setShortcut(QKeySequence.Quit) work.triggered.connect(self.close) self.file_menu.addAction(work) # Initialize the list of "recent" files for the File sub-menu. # These files were not necessarily open at shutdown, just sometime # in the not too distant past. self.recent_files = self._read_flist('mainwindow/recent_files') # -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= # Functions related to shutdown and management of settings. # # Factor out the job of reading/writing a list of files in the settings. # Input is a settings array key string like 'mainwindow/recent_files' # Output is a possibly empty list of canonical-file-path strings. def _read_flist(self, array_key): f_list = [] f_count = self.settings.beginReadArray(array_key) for f in range(f_count): # which may be 0 self.settings.setArrayIndex(f) f_list.append( self.settings.value('filepath') ) self.settings.endArray() return f_list # Input is an array key and a possibly empty list of path strings def _write_flist(self, file_list, array_key): if len(file_list): self.settings.beginWriteArray( array_key, len(file_list) ) for f in range(len(file_list)) : self.settings.setArrayIndex( f ) self.settings.setValue( 'filepath',file_list[f] ) self.settings.endArray() # Reimplement QWidget.closeEvent in order to save any open files # and update the settings. def closeEvent(self, event): # If there are any unsaved books, ask the user if they should be # saved. If the answer is yes, try to do so. unsaved = [] for (seq, book_object) in self.open_books.items() : if book_object.get_save_needed() : unsaved.append(seq) if len(unsaved): if len(unsaved) == 1 : msg = _TR('Shutdown message', 'There is one unsaved file') else : msg = _TR('Shutdown message', 'There are %n unsaved files', n=len(unsaved)) ret = utilities.save_discard_cancel_msg( msg, _TR('Shutdown message', 'Save, Discard changes, or Cancel Quit?') ) if ret is None : # user wants to cancel shutdown event.ignore() return if ret : # User want to save. Focus each unsaved file and call _save. # For all but "Untitled-n" documents this will be silent. For # those, it will open a save-as dialog. We ignore the return # from this because we cannot distinguish between a cancelled # file-open dialog and a file write error. for seq in unsaved : self.focus_me(seq) self._save() # Clear the settings so that old values don't hang around self.settings.clear() # Tell the submodules to save their current global values. colors.shutdown(self.settings) fonts.shutdown(self.settings) dictionaries.shutdown(self.settings) paths.shutdown(self.settings) # Save the list of currently-open files in the settings, but do not # save any whose filename matches "Untitled-#" because that is an # unsaved New file (which the user chose not to save, above). open_paths = [] for (index, book_obj) in self.open_books.items() : if not book_obj.get_book_name().startswith('Untitled-'): open_paths.append( book_obj.get_book_full_path() ) self._write_flist( open_paths, 'mainwindow/open_files' ) # Save the list of "recent" files in the settings. self._write_flist(self.recent_files, 'mainwindow/recent_files') # Save this window's position and size and splitter state self.settings.setValue("mainwindow/size",self.size()) self.settings.setValue("mainwindow/position",self.pos()) self.settings.setValue("mainwindow/splitter",self.splitter.saveState()) # and that's it, we are done finished, over & out. event.accept()
def __init__(self, app): QMainWindow.__init__(self, None) self.l.debug('Initializing MainWindow ...') self.theSun = SunSimulator() self.timeZones = [] for x in QTimeZone.availableTimeZoneIds(): tz = QTimeZone(x) self.timeZones.append(tz) #print(" {} {} {}".format(str(tz.id()), tz.comment(), tz.hasDaylightTime())) #self.revLookup = {} #idx = 0 #for d in self.timeZones: # self.revLookup[d[1]] = idx # idx += 1 self.setWindowTitle('Shadow') # app.setWindowIcon(QIcon(':/icons/mynpad.png')) # # if os.name == 'nt': # # On Windows, make sure to use a unique Application User Model Id, otherwise # # Windows shows the default python icon in the taskbar # # see http://stackoverflow.com/questions/1551605/how-to-set-applications-taskbar-icon-in-windows-7 # myappid = 'afester.mynpad' # import ctypes; ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID(myappid) self.theApplication = app app.aboutToQuit.connect(self.saveState) # read the local configuration file iniPath = 'shadow.ini' if not os.path.exists(iniPath): iniPath = os.path.join(expanduser("~"), iniPath) self.settings = Settings(iniPath) self.settings.load() # Set up the menu bar menuBar = QMenuBar(self) exitAction = QAction("Exit", self, triggered=self.theApplication.exit) fileMenu = menuBar.addMenu("&File") fileMenu.addAction(exitAction) aboutAction = QAction("About ...", self, triggered = self.handleAbout) helpMenu = menuBar.addMenu("&Help") helpMenu.addAction(aboutAction) self.setMenuBar(menuBar) self.centralWidget = QWidget() self.left = DataWidget(self.centralWidget) self.right = ShadowWidget(self.centralWidget) # Create time zone selector self.left.ui.timeZoneComboBox.clear() for tz in self.timeZones: # TODO: Hack (?) displayId = tz.id().data().decode(encoding="UTF-8") if not displayId.startswith('UTC'): utcOffset = tz.displayName(QTimeZone.GenericTime, QTimeZone.OffsetName) #self.left.ui.timeZoneComboBox.addItem("({}) {} - {}".format(utcOffset, displayId, tz.comment())) self.left.ui.timeZoneComboBox.addItem("({}) {}".format(utcOffset, displayId)) self.left.ui.timeZoneComboBox.setCurrentIndex(self.settings.getTzIndex()) self.left.ui.timeZoneComboBox.currentIndexChanged.connect(self.setTimeZone) self.left.ui.dateEdit.dateChanged.connect(self.updateDate) self.left.ui.timeEdit.timeChanged.connect(self.updateTime) self.left.ui.timeSlider.valueChanged.connect(self.slideTime) layout = QHBoxLayout() self.centralWidget.setLayout(layout) layout.addWidget(self.left) layout.addWidget(self.right) layout.setStretch(0, 0); layout.setStretch(1, 1); self.setCentralWidget(self.centralWidget) # Reset main window size and position pos = self.settings.getMainWindowPos() self.move(pos.x(), pos.y()) size = self.settings.getMainWindowSize() self.resize(size) # sample values self.left.ui.treeHeightLineEdit.setValue(10) self.left.ui.latitudeLineEdit.setValue(48.1) self.left.ui.LongitudeLineEdit.setValue(11.6) self.left.ui.dateEdit.setDate(QDate(2015, 9, 11)) self.left.ui.timeEdit.setTime(QTime(8, 0))
class FrontPanel(QDialog): """This is FiledSensor test program front panel class""" def __init__(self): super().__init__() # GroupBox Initialization self.mainlayout = QGridLayout() # basicinfo layout self.names = [] self.menuBar = QMenuBar() # PushButton Initialization self.BeginTestButton = QPushButton('开始测试') self.CancelTestButton = QPushButton('取消测试') self.PauseTestButton = QPushButton('暂停测试') self.SaveBasicinfoButton = QPushButton('保存基本信息') self.initUI() def initUI(self): """initialise the UI""" self.BasicinfoList() self.ButtonList() self.CreateMenu() self.StretchSet() self.mainlayout.addWidget(self.SaveBasicinfoButton, 12, 0, 1, 2) self.mainlayout.setMenuBar(self.menuBar) self.setLayout(self.mainlayout) self.setGeometry(300, 100, 900, 700) # 设置窗口位置大小 self.setWindowTitle('FieldSensor') self.show() def CreateMenu(self): """create the menu""" file_menu = self.menuBar.addMenu('&File') open_action = QAction('&打开', self) exit_action = QAction('&退出', self) file_menu.addAction(open_action) file_menu.addAction(exit_action) exit_action.triggered.connect(self.accept) def ButtonList(self): names = [self.BeginTestButton, self.CancelTestButton, self.PauseTestButton] for i in range(3): self.mainlayout.addWidget(names[i], i + 4, 4) def BasicinfoList(self): """basicinfo layout set""" certificate_num_label = QLabel('证书编号') certificate_serial_label = QLabel('证书序列号') manufacturer_label = QLabel('生产厂家') device_name_label = QLabel('设备名称') custom_address_label = QLabel('客户地址') custom_name_label = QLabel('客户名称') calibration_address_label = QLabel('校准地点') temperature_label = QLabel('温 度') humidity_label = QLabel('湿 度') tester_label = QLabel('测试人员') date_label = QLabel('测试日期') # LineEdit Initialization certificatenumber = QLineEdit() certificateserial = QLineEdit() manufacturer = QLineEdit() devicename = QLineEdit() customaddress = QLineEdit() customname = QLineEdit() calibrationaddress = QLineEdit() temperature = QLineEdit() humidity = QLineEdit() tester = QLineEdit() date = QLineEdit() self.names = [certificate_num_label, certificatenumber, certificate_serial_label, certificateserial, manufacturer_label, manufacturer, device_name_label, devicename, custom_address_label, customaddress, custom_name_label, customname, calibration_address_label, calibrationaddress, temperature_label, temperature, humidity_label, humidity, tester_label, tester, date_label, date] for i in range(22): if i % 2 == 0: self.mainlayout.addWidget(self.names[i], i / 2, 0) else: self.mainlayout.addWidget(self.names[i], (i - 1) / 2, 1) def StretchSet(self): # set column stretch self.mainlayout.setColumnStretch(0, 0.5) self.mainlayout.setColumnStretch(1, 2) self.mainlayout.setColumnStretch(2, 1) self.mainlayout.setColumnStretch(3, 1)
def init(self): self.main_vbox = QVBoxLayout() self.config_file="" self.plot_token=None self.labels=[] self.fig = Figure(figsize=(2.5,2), dpi=100) self.plot_id=[] self.canvas = FigureCanvas(self.fig) # a gtk.DrawingArea self.zero_frame_enable=False self.zero_frame_list=[] self.plot_title="" self.gen_colors(1) toolbar=QToolBar() toolbar.setIconSize(QSize(48, 48)) self.tb_save = QAction(QIcon(os.path.join(get_image_file_path(),"save.png")), _("Save graph"), self) self.tb_save.triggered.connect(self.callback_plot_save) toolbar.addAction(self.tb_save) self.tb_refresh = QAction(QIcon(os.path.join(get_image_file_path(),"refresh.png")), _("Refresh graph"), self) self.tb_refresh .triggered.connect(self.callback_refresh) toolbar.addAction(self.tb_refresh ) nav_bar=NavigationToolbar(self.canvas,self) toolbar.addWidget(nav_bar) self.fig.canvas.mpl_connect('motion_notify_event', self.mouse_move) menubar = QMenuBar() file_menu = menubar.addMenu("File") self.menu_save=file_menu.addAction(_("&Save")) self.menu_save.triggered.connect(self.callback_save) self.menu_save_as=file_menu.addAction(_("&Save as")) self.menu_save_as.triggered.connect(self.callback_plot_save) key_menu = menubar.addMenu('&Key') key_menu = menubar.addMenu('&Color') self.menu_black=key_menu.addAction(_("&Black")) self.menu_black.triggered.connect(self.callback_black) self.menu_rainbow=key_menu.addAction(_("&Rainbow")) self.menu_rainbow.triggered.connect(self.callback_rainbow) axis_menu = menubar.addMenu('&Color') menu=axis_menu.addAction(_("&Autoscale")) menu.triggered.connect(self.callback_autoscale_y) menu=axis_menu.addAction(_("&Set log scale y")) menu.triggered.connect(self.callback_toggle_log_scale_y) menu=axis_menu.addAction(_("&Set log scale x")) menu.triggered.connect(self.callback_toggle_log_scale_x) menu=axis_menu.addAction(_("&Set log scale x")) menu.triggered.connect(self.callback_toggle_log_scale_x) self.menu_rainbow=key_menu.addAction(_("&Label data")) self.menu_rainbow.triggered.connect(self.callback_toggle_label_data) math_menu = menubar.addMenu('&Math') menu=math_menu.addAction(_("&Subtract first point")) menu.triggered.connect(self.callback_toggle_subtract_first_point) menu=math_menu.addAction(_("&Add min point")) menu.triggered.connect(self.callback_toggle_add_min) menu=math_menu.addAction(_("&Invert y-axis")) menu.triggered.connect(self.callback_toggle_invert_y) menu=math_menu.addAction(_("&Norm to 1.0 y")) menu.triggered.connect(self.callback_normtoone_y) menu=math_menu.addAction(_("&Norm to peak of all data")) menu.triggered.connect(self.callback_norm_to_peak_of_all_data) menu=math_menu.addAction(_("&Heat map")) menu.triggered.connect(self.callback_set_heat_map) menu=math_menu.addAction(_("&Heat map edit")) menu.triggered.connect(self.callback_heat_map_edit) menu=math_menu.addAction(_("&xy plot")) menu.triggered.connect(self.callback_set_xy_plot) self.main_vbox.addWidget(menubar) self.main_vbox.addWidget(toolbar) self.canvas.figure.patch.set_facecolor('white') self.canvas.setMinimumSize(800, 350) self.main_vbox.addWidget(self.canvas) self.setLayout(self.main_vbox)
def __init__(self): QWidget.__init__(self) self.dump_dir=os.path.join(os.getcwd(),"light_dump") find_models() self.setWindowIcon(QIcon(os.path.join(get_image_file_path(),"image.png"))) self.setMinimumSize(1000, 600) self.edit_list=[] self.line_number=[] self.articles=[] input_files=[] input_files.append(os.path.join(os.getcwd(),"light_dump","light_2d_photons.dat")) input_files.append(os.path.join(os.getcwd(),"light_dump","light_2d_photons_asb.dat")) input_files.append(os.path.join(os.getcwd(),"light_dump","reflect.dat")) plot_labels=[] plot_labels.append("Photon distribution") plot_labels.append("Photon distribution absorbed") plot_labels.append("Reflection") self.setGeometry(300, 300, 600, 600) self.setWindowTitle(_("Optical simulation editor (www.gpvdm.com)")) self.setWindowIcon(QIcon(os.path.join(get_image_file_path(),"optics.png"))) self.main_vbox=QVBoxLayout() menubar = QMenuBar() file_menu = menubar.addMenu('&File') self.menu_refresh=file_menu.addAction(_("&Refresh")) self.menu_refresh.triggered.connect(self.update) self.menu_close=file_menu.addAction(_("&Close")) self.menu_close.triggered.connect(self.callback_close) self.main_vbox.addWidget(menubar) toolbar=QToolBar() toolbar.setIconSize(QSize(48, 48)) self.run = QAction(QIcon(os.path.join(get_image_file_path(),"play.png")), _("Run"), self) self.run.triggered.connect(self.callback_run) toolbar.addAction(self.run) label=QLabel(_("Wavelengths:")) toolbar.addWidget(label) self.cb = QComboBox() self.update_cb() toolbar.addWidget(self.cb) self.cb.currentIndexChanged.connect(self.mode_changed) label=QLabel(_("Optical model:")) toolbar.addWidget(label) self.cb_model = QComboBox() toolbar.addWidget(self.cb_model) self.update_cb_model() self.cb_model.activated.connect(self.on_cb_model_changed) label=QLabel(_("Solar spectrum:")) toolbar.addWidget(label) self.light_source_model = QComboBox() self.update_light_source_model() toolbar.addWidget(self.light_source_model) self.light_source_model.activated.connect(self.on_light_source_model_changed) spacer = QWidget() spacer.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) toolbar.addWidget(spacer) self.help = QAction(QIcon(os.path.join(get_image_file_path(),"help.png")), 'Help', self) self.help.triggered.connect(self.callback_help) toolbar.addAction(self.help) self.main_vbox.addWidget(toolbar) self.progress_window=progress_class() self.notebook = QTabWidget() self.notebook.setMovable(True) self.fig_photon_density = band_graph() self.fig_photon_density.set_data_file("light_1d_photons_tot_norm.dat") self.fig_photon_density.init() self.notebook.addTab(self.fig_photon_density,"Photon density") self.fig_photon_abs = band_graph() self.fig_photon_abs.set_data_file("light_1d_photons_tot_abs_norm.dat") self.fig_photon_abs.init() self.notebook.addTab(self.fig_photon_abs,"Photon absorbed") widget=tab_class() widget.init("light.inp","Optical setup") self.notebook.addTab(widget,"Optical setup") self.plot_widgets=[] self.progress_window.start() for i in range(0,len(input_files)): self.plot_widgets.append(plot_widget()) self.plot_widgets[i].init() self.plot_widgets[i].set_labels([plot_labels[0]]) self.plot_widgets[i].load_data([input_files[i]],os.path.splitext(input_files[i])[0]+".oplot") self.plot_widgets[i].do_plot() #self.plot_widgets[i].show() self.notebook.addTab(self.plot_widgets[i],plot_labels[i]) self.fig_photon_density.draw_graph() self.fig_photon_abs.draw_graph() self.progress_window.stop() self.main_vbox.addWidget(self.notebook) self.setLayout(self.main_vbox) return
class MainWindow_Ui(QMainWindow): def __init__(self, persepolis_setting): super().__init__() # MainWindow self.persepolis_setting = persepolis_setting # add support for other languages locale = str(self.persepolis_setting.value('settings/locale')) QLocale.setDefault(QLocale(locale)) self.translator = QTranslator() if self.translator.load(':/translations/locales/ui_' + locale, 'ts'): QCoreApplication.installTranslator(self.translator) # set ui direction ui_direction = self.persepolis_setting.value('ui_direction') if ui_direction == 'rtl': self.setLayoutDirection(Qt.RightToLeft) elif ui_direction in 'ltr': self.setLayoutDirection(Qt.LeftToRight) icons = ':/' + \ str(self.persepolis_setting.value('settings/icons')) + '/' self.setWindowTitle(QCoreApplication.translate("mainwindow_ui_tr", "Persepolis Download Manager")) self.setWindowIcon(QIcon.fromTheme('persepolis', QIcon(':/persepolis.svg'))) self.centralwidget = QWidget(self) self.verticalLayout = QVBoxLayout(self.centralwidget) # enable drag and drop self.setAcceptDrops(True) # frame self.frame = QFrame(self.centralwidget) # download_table_horizontalLayout download_table_horizontalLayout = QHBoxLayout() tabels_splitter = QSplitter(Qt.Horizontal) # category_tree self.category_tree_qwidget = QWidget(self) category_tree_verticalLayout = QVBoxLayout() self.category_tree = CategoryTreeView(self) category_tree_verticalLayout.addWidget(self.category_tree) self.category_tree_model = QStandardItemModel() self.category_tree.setModel(self.category_tree_model) category_table_header = [QCoreApplication.translate("mainwindow_ui_tr", 'Category')] self.category_tree_model.setHorizontalHeaderLabels( category_table_header) self.category_tree.header().setStretchLastSection(True) self.category_tree.header().setDefaultAlignment(Qt.AlignCenter) # queue_panel self.queue_panel_widget = QWidget(self) queue_panel_verticalLayout_main = QVBoxLayout(self.queue_panel_widget) # queue_panel_show_button self.queue_panel_show_button = QPushButton(self) queue_panel_verticalLayout_main.addWidget(self.queue_panel_show_button) # queue_panel_widget_frame self.queue_panel_widget_frame = QFrame(self) self.queue_panel_widget_frame.setFrameShape(QFrame.StyledPanel) self.queue_panel_widget_frame.setFrameShadow(QFrame.Raised) queue_panel_verticalLayout_main.addWidget( self.queue_panel_widget_frame) queue_panel_verticalLayout = QVBoxLayout(self.queue_panel_widget_frame) queue_panel_verticalLayout_main.setContentsMargins(50, -1, 50, -1) # start_end_frame self.start_end_frame = QFrame(self) # start time start_verticalLayout = QVBoxLayout(self.start_end_frame) self.start_checkBox = QCheckBox(self) start_verticalLayout.addWidget(self.start_checkBox) self.start_frame = QFrame(self) self.start_frame.setFrameShape(QFrame.StyledPanel) self.start_frame.setFrameShadow(QFrame.Raised) start_frame_verticalLayout = QVBoxLayout(self.start_frame) self.start_time_qDataTimeEdit = QDateTimeEdit(self.start_frame) self.start_time_qDataTimeEdit.setDisplayFormat('H:mm') start_frame_verticalLayout.addWidget(self.start_time_qDataTimeEdit) start_verticalLayout.addWidget(self.start_frame) # end time self.end_checkBox = QCheckBox(self) start_verticalLayout.addWidget(self.end_checkBox) self.end_frame = QFrame(self) self.end_frame.setFrameShape(QFrame.StyledPanel) self.end_frame.setFrameShadow(QFrame.Raised) end_frame_verticalLayout = QVBoxLayout(self.end_frame) self.end_time_qDateTimeEdit = QDateTimeEdit(self.end_frame) self.end_time_qDateTimeEdit.setDisplayFormat('H:mm') end_frame_verticalLayout.addWidget(self.end_time_qDateTimeEdit) start_verticalLayout.addWidget(self.end_frame) self.reverse_checkBox = QCheckBox(self) start_verticalLayout.addWidget(self.reverse_checkBox) queue_panel_verticalLayout.addWidget(self.start_end_frame) # limit_after_frame self.limit_after_frame = QFrame(self) # limit_checkBox limit_verticalLayout = QVBoxLayout(self.limit_after_frame) self.limit_checkBox = QCheckBox(self) limit_verticalLayout.addWidget(self.limit_checkBox) # limit_frame self.limit_frame = QFrame(self) self.limit_frame.setFrameShape(QFrame.StyledPanel) self.limit_frame.setFrameShadow(QFrame.Raised) limit_verticalLayout.addWidget(self.limit_frame) limit_frame_verticalLayout = QVBoxLayout(self.limit_frame) # limit_spinBox limit_frame_horizontalLayout = QHBoxLayout() self.limit_spinBox = QDoubleSpinBox(self) self.limit_spinBox.setMinimum(1) self.limit_spinBox.setMaximum(1023) limit_frame_horizontalLayout.addWidget(self.limit_spinBox) # limit_comboBox self.limit_comboBox = QComboBox(self) self.limit_comboBox.addItem("") self.limit_comboBox.addItem("") limit_frame_horizontalLayout.addWidget(self.limit_comboBox) limit_frame_verticalLayout.addLayout(limit_frame_horizontalLayout) # limit_pushButton self.limit_pushButton = QPushButton(self) limit_frame_verticalLayout.addWidget(self.limit_pushButton) # after_checkBox self.after_checkBox = QtWidgets.QCheckBox(self) limit_verticalLayout.addWidget(self.after_checkBox) # after_frame self.after_frame = QtWidgets.QFrame(self) self.after_frame.setFrameShape(QtWidgets.QFrame.StyledPanel) self.after_frame.setFrameShadow(QtWidgets.QFrame.Raised) limit_verticalLayout.addWidget(self.after_frame) after_frame_verticalLayout = QVBoxLayout(self.after_frame) # after_comboBox self.after_comboBox = QComboBox(self) self.after_comboBox.addItem("") after_frame_verticalLayout.addWidget(self.after_comboBox) # after_pushButton self.after_pushButton = QPushButton(self) after_frame_verticalLayout.addWidget(self.after_pushButton) queue_panel_verticalLayout.addWidget(self.limit_after_frame) category_tree_verticalLayout.addWidget(self.queue_panel_widget) # keep_awake_checkBox self.keep_awake_checkBox = QCheckBox(self) queue_panel_verticalLayout.addWidget(self.keep_awake_checkBox) self.category_tree_qwidget.setLayout(category_tree_verticalLayout) tabels_splitter.addWidget(self.category_tree_qwidget) # download table widget self.download_table_content_widget = QWidget(self) download_table_content_widget_verticalLayout = QVBoxLayout( self.download_table_content_widget) self.download_table = DownloadTableWidget(self) download_table_content_widget_verticalLayout.addWidget( self.download_table) tabels_splitter.addWidget(self.download_table_content_widget) self.download_table.setColumnCount(13) self.download_table.setSelectionBehavior(QAbstractItemView.SelectRows) self.download_table.setEditTriggers(QAbstractItemView.NoEditTriggers) self.download_table.verticalHeader().hide() # hide gid and download dictioanry section self.download_table.setColumnHidden(8, True) self.download_table.setColumnHidden(9, True) download_table_header = [QCoreApplication.translate("mainwindow_ui_tr", 'File Name'), QCoreApplication.translate("mainwindow_ui_tr",'Status'), QCoreApplication.translate("mainwindow_ui_tr", 'Size'), QCoreApplication.translate("mainwindow_ui_tr", 'Downloaded'), QCoreApplication.translate("mainwindow_ui_tr", 'Percentage'), QCoreApplication.translate("mainwindow_ui_tr", 'Connections'), QCoreApplication.translate("mainwindow_ui_tr", 'Transfer rate'), QCoreApplication.translate("mainwindow_ui_tr",'Estimated time left'), 'Gid', QCoreApplication.translate("mainwindow_ui_tr",'Link'), QCoreApplication.translate("mainwindow_ui_tr", 'First try date'), QCoreApplication.translate("mainwindow_ui_tr", 'Last try date'), QCoreApplication.translate("mainwindow_ui_tr",'Category')] self.download_table.setHorizontalHeaderLabels(download_table_header) # fixing the size of download_table when window is Maximized! self.download_table.horizontalHeader().setSectionResizeMode(0) self.download_table.horizontalHeader().setStretchLastSection(True) tabels_splitter.setStretchFactor(0, 3) # category_tree width tabels_splitter.setStretchFactor(1, 10) # ratio of tables's width download_table_horizontalLayout.addWidget(tabels_splitter) self.frame.setLayout(download_table_horizontalLayout) self.verticalLayout.addWidget(self.frame) self.setCentralWidget(self.centralwidget) # menubar self.menubar = QMenuBar(self) self.menubar.setGeometry(QRect(0, 0, 600, 24)) self.setMenuBar(self.menubar) fileMenu = self.menubar.addMenu(QCoreApplication.translate("mainwindow_ui_tr", '&File')) editMenu = self.menubar.addMenu(QCoreApplication.translate("mainwindow_ui_tr", '&Edit')) viewMenu = self.menubar.addMenu(QCoreApplication.translate("mainwindow_ui_tr", '&View')) downloadMenu = self.menubar.addMenu(QCoreApplication.translate("mainwindow_ui_tr", '&Download')) queueMenu = self.menubar.addMenu(QCoreApplication.translate("mainwindow_ui_tr", '&Queue')) videoFinderMenu = self.menubar.addMenu(QCoreApplication.translate("mainwindow_ui_tr", 'V&ideo Finder')) helpMenu = self.menubar.addMenu(QCoreApplication.translate("mainwindow_ui_tr", '&Help')) # viewMenu submenus sortMenu = viewMenu.addMenu(QCoreApplication.translate("mainwindow_ui_tr", 'Sort by')) # statusbar self.statusbar = QStatusBar(self) self.setStatusBar(self.statusbar) self.statusbar.showMessage(QCoreApplication.translate("mainwindow_ui_tr", "Persepolis Download Manager")) # toolBar self.toolBar2 = QToolBar(self) self.addToolBar(QtCore.Qt.TopToolBarArea, self.toolBar2) self.toolBar2.setWindowTitle(QCoreApplication.translate("mainwindow_ui_tr", 'Menu')) self.toolBar2.setFloatable(False) self.toolBar2.setMovable(False) self.toolBar = QToolBar(self) self.addToolBar(QtCore.Qt.TopToolBarArea, self.toolBar) self.toolBar.setWindowTitle(QCoreApplication.translate("mainwindow_ui_tr", 'Toolbar')) self.toolBar.setFloatable(False) self.toolBar.setMovable(False) #toolBar and menubar and actions self.videoFinderAddLinkAction = QAction(QIcon(icons + 'video_finder'), QCoreApplication.translate("mainwindow_ui_tr", 'Find Video Links'), self, statusTip=QCoreApplication.translate("mainwindow_ui_tr", 'Download video or audio from Youtube, Vimeo, etc...'), triggered=self.showVideoFinderAddLinkWindow) QShortcut(QKeySequence('Ctrl+I'), self, self.showVideoFinderAddLinkWindow) videoFinderMenu.addAction(self.videoFinderAddLinkAction) self.stopAllAction = QAction(QIcon(icons + 'stop_all'), QCoreApplication.translate("mainwindow_ui_tr", 'Stop all active downloads'), self, statusTip='Stop all active downloads', triggered=self.stopAllDownloads) downloadMenu.addAction(self.stopAllAction) self.sort_file_name_Action = QAction( QCoreApplication.translate("mainwindow_ui_tr", 'File name'), self, triggered=self.sortByName) sortMenu.addAction(self.sort_file_name_Action) self.sort_file_size_Action = QAction( QCoreApplication.translate("mainwindow_ui_tr", 'File size'), self, triggered=self.sortBySize) sortMenu.addAction(self.sort_file_size_Action) self.sort_first_try_date_Action = QAction( QCoreApplication.translate("mainwindow_ui_tr", 'First try date'), self, triggered=self.sortByFirstTry) sortMenu.addAction(self.sort_first_try_date_Action) self.sort_last_try_date_Action = QAction( QCoreApplication.translate("mainwindow_ui_tr", 'Last try date'), self, triggered=self.sortByLastTry) sortMenu.addAction(self.sort_last_try_date_Action) self.sort_download_status_Action = QAction( QCoreApplication.translate("mainwindow_ui_tr", 'Download status'), self, triggered=self.sortByStatus) sortMenu.addAction(self.sort_download_status_Action) self.trayAction = QAction(QCoreApplication.translate("mainwindow_ui_tr", 'Show system tray icon'), self, statusTip=QCoreApplication.translate("mainwindow_ui_tr", "Show/Hide system tray icon"), triggered=self.showTray) self.trayAction.setCheckable(True) viewMenu.addAction(self.trayAction) self.showMenuBarAction = QAction( QCoreApplication.translate("mainwindow_ui_tr", 'Show menubar'), self, statusTip=QCoreApplication.translate("mainwindow_ui_tr", 'Show menubar'), triggered=self.showMenuBar) self.showMenuBarAction.setCheckable(True) viewMenu.addAction(self.showMenuBarAction) self.showSidePanelAction = QAction( QCoreApplication.translate("mainwindow_ui_tr", 'Show side panel'), self, statusTip=QCoreApplication.translate("mainwindow_ui_tr", 'Show side panel'), triggered=self.showSidePanel) self.showSidePanelAction.setCheckable(True) viewMenu.addAction(self.showSidePanelAction) self.minimizeAction = QAction(QIcon(icons + 'minimize'), QCoreApplication.translate("mainwindow_ui_tr", 'Minimize to system tray'), self, statusTip=QCoreApplication.translate("mainwindow_ui_tr", "Minimize to system tray"), triggered=self.minMaxTray) QShortcut(QKeySequence('Ctrl+W'), self, self.minMaxTray) viewMenu.addAction(self.minimizeAction) self.addlinkAction = QAction(QIcon(icons + 'add'), QCoreApplication.translate("mainwindow_ui_tr", 'Add New Download Link'), self, statusTip=QCoreApplication.translate("mainwindow_ui_tr", "Add New Download Link"), triggered=self.addLinkButtonPressed) QShortcut(QKeySequence('Ctrl+N'), self, self.addLinkButtonPressed) fileMenu.addAction(self.addlinkAction) self.addtextfileAction = QAction(QIcon(icons + 'file'), QCoreApplication.translate("mainwindow_ui_tr", 'Import links from text file'), self, statusTip=QCoreApplication.translate("mainwindow_ui_tr", 'Create a Text file and put links in it.line by line!'), triggered=self.importText) fileMenu.addAction(self.addtextfileAction) self.resumeAction = QAction(QIcon(icons + 'play'), QCoreApplication.translate("mainwindow_ui_tr", 'Resume Download'), self, statusTip=QCoreApplication.translate("mainwindow_ui_tr", "Resume Download"), triggered=self.resumeButtonPressed) QShortcut(QKeySequence('Ctrl+R'), self, self.resumeButtonPressed) downloadMenu.addAction(self.resumeAction) self.pauseAction = QAction(QIcon(icons + 'pause'), QCoreApplication.translate("mainwindow_ui_tr", 'Pause Download'), self, statusTip=QCoreApplication.translate("mainwindow_ui_tr", "Pause Download"), triggered=self.pauseButtonPressed) QShortcut(QKeySequence('Ctrl+C'), self, self.pauseButtonPressed) downloadMenu.addAction(self.pauseAction) self.stopAction = QAction(QIcon(icons + 'stop'), QCoreApplication.translate("mainwindow_ui_tr", 'Stop Download'), self, statusTip=QCoreApplication.translate("mainwindow_ui_tr", "Stop/Cancel Download"), triggered=self.stopButtonPressed) QShortcut(QKeySequence('Ctrl+S'), self, self.stopButtonPressed) downloadMenu.addAction(self.stopAction) self.propertiesAction = QAction(QIcon(icons + 'setting'), QCoreApplication.translate("mainwindow_ui_tr", 'Properties'), self, statusTip=QCoreApplication.translate("mainwindow_ui_tr", "Properties"), triggered=self.propertiesButtonPressed) QShortcut(QKeySequence('Ctrl+P'), self, self.propertiesButtonPressed) downloadMenu.addAction(self.propertiesAction) self.progressAction = QAction(QIcon(icons + 'window'), QCoreApplication.translate("mainwindow_ui_tr", 'Progress'), self, statusTip=QCoreApplication.translate("mainwindow_ui_tr", "Progress"), triggered=self.progressButtonPressed) QShortcut(QKeySequence('Ctrl+Z'), self, self.progressButtonPressed) downloadMenu.addAction(self.progressAction) self.openFileAction = QAction(QIcon( icons + 'file'), QCoreApplication.translate("mainwindow_ui_tr", 'Open file'), self, statusTip=QCoreApplication.translate("mainwindow_ui_tr", 'Open file'), triggered=self.openFile) fileMenu.addAction(self.openFileAction) self.openDownloadFolderAction = QAction(QIcon( icons + 'folder'), QCoreApplication.translate("mainwindow_ui_tr", 'Open download folder'), self, statusTip=QCoreApplication.translate("mainwindow_ui_tr", 'Open download folder'), triggered=self.openDownloadFolder) fileMenu.addAction(self.openDownloadFolderAction) self.openDefaultDownloadFolderAction = QAction(QIcon( icons + 'folder'), QCoreApplication.translate("mainwindow_ui_tr", 'Open default download folder'), self, statusTip=QCoreApplication.translate("mainwindow_ui_tr", 'Open default download folder'), triggered=self.openDefaultDownloadFolder) fileMenu.addAction(self.openDefaultDownloadFolderAction) self.exitAction = QAction(QIcon(icons + 'exit'), QCoreApplication.translate("mainwindow_ui_tr", 'Exit'), self, statusTip=QCoreApplication.translate("mainwindow_ui_tr", "Exit"), triggered=self.closeEvent) QShortcut(QKeySequence('Ctrl+Q'), self, self.closeEvent) fileMenu.addAction(self.exitAction) self.clearAction = QAction(QIcon(icons + 'multi_remove'), QCoreApplication.translate("mainwindow_ui_tr", 'Clear download list'), self, statusTip=QCoreApplication.translate("mainwindow_ui_tr", 'Clear all items in download list'), triggered=self.clearDownloadList) editMenu.addAction(self.clearAction) self.removeSelectedAction = QAction(QIcon(icons + 'remove'), QCoreApplication.translate("mainwindow_ui_tr", 'Remove selected downloads from list'), self, statusTip=QCoreApplication.translate("mainwindow_ui_tr", 'Remove selected downloads form list'), triggered=self.removeSelected) editMenu.addAction(self.removeSelectedAction) self.removeSelectedAction.setEnabled(False) self.deleteSelectedAction = QAction(QIcon(icons + 'trash'), QCoreApplication.translate("mainwindow_ui_tr", 'Delete selected download files'), self, statusTip=QCoreApplication.translate("mainwindow_ui_tr", 'Delete selected download files'), triggered=self.deleteSelected) editMenu.addAction(self.deleteSelectedAction) self.deleteSelectedAction.setEnabled(False) self.createQueueAction = QAction(QIcon(icons + 'add_queue'), QCoreApplication.translate("mainwindow_ui_tr", 'Create new queue'), self, statusTip=QCoreApplication.translate("mainwindow_ui_tr", 'Create new download queue'), triggered=self.createQueue) queueMenu.addAction(self.createQueueAction) self.removeQueueAction = QAction(QIcon(icons + 'remove_queue'), QCoreApplication.translate("mainwindow_ui_tr", 'Remove this queue'), self, statusTip=QCoreApplication.translate("mainwindow_ui_tr", 'Remove this queue'), triggered=self.removeQueue) queueMenu.addAction(self.removeQueueAction) self.startQueueAction = QAction(QIcon( icons + 'start_queue'), QCoreApplication.translate("mainwindow_ui_tr", 'Start this queue'), self, statusTip=QCoreApplication.translate("mainwindow_ui_tr", 'Start this queue'), triggered=self.startQueue) queueMenu.addAction(self.startQueueAction) self.stopQueueAction = QAction(QIcon( icons + 'stop_queue'), QCoreApplication.translate("mainwindow_ui_tr", 'Stop this queue'), self, statusTip=QCoreApplication.translate("mainwindow_ui_tr", 'Stop this queue'), triggered=self.stopQueue) queueMenu.addAction(self.stopQueueAction) self.moveUpSelectedAction = QAction(QIcon(icons + 'multi_up'), QCoreApplication.translate("mainwindow_ui_tr", 'Move up selected items'), self, statusTip=QCoreApplication.translate("mainwindow_ui_tr", 'Move currently selected items up by one row'), triggered=self.moveUpSelected) queueMenu.addAction(self.moveUpSelectedAction) self.moveDownSelectedAction = QAction(QIcon(icons + 'multi_down'), QCoreApplication.translate("mainwindow_ui_tr", 'Move down selected items'), self, statusTip=QCoreApplication.translate("mainwindow_ui_tr", 'Move currently selected items down by one row'), triggered=self.moveDownSelected) queueMenu.addAction(self.moveDownSelectedAction) self.preferencesAction = QAction(QIcon(icons + 'preferences'), QCoreApplication.translate("mainwindow_ui_tr", 'Preferences'), self, statusTip=QCoreApplication.translate("mainwindow_ui_tr", 'Preferences'), triggered=self.openPreferences, menuRole=5) editMenu.addAction(self.preferencesAction) self.aboutAction = QAction(QIcon( icons + 'about'), QCoreApplication.translate("mainwindow_ui_tr", 'About'), self, statusTip=QCoreApplication.translate("mainwindow_ui_tr", 'About'), triggered=self.openAbout, menuRole=4) helpMenu.addAction(self.aboutAction) self.issueAction = QAction(QIcon(icons + 'about'), QCoreApplication.translate("mainwindow_ui_tr", 'Report an issue'), self, statusTip=QCoreApplication.translate("mainwindow_ui_tr", 'Report an issue'), triggered=self.reportIssue) helpMenu.addAction(self.issueAction) self.updateAction = QAction(QIcon(icons + 'about'), QCoreApplication.translate("mainwindow_ui_tr", 'Check for newer version'), self, statusTip=QCoreApplication.translate("mainwindow_ui_tr", 'Check for newer release'), triggered=self.newUpdate) helpMenu.addAction(self.updateAction) self.logAction = QAction(QIcon(icons + 'about'), QCoreApplication.translate("mainwindow_ui_tr", 'Show log file'), self, statusTip=QCoreApplication.translate("mainwindow_ui_tr", 'Help'), triggered=self.showLog) helpMenu.addAction(self.logAction) self.helpAction = QAction(QIcon(icons + 'about'), QCoreApplication.translate("mainwindow_ui_tr", 'Help'), self, statusTip=QCoreApplication.translate("mainwindow_ui_tr", 'Help'), triggered=self.persepolisHelp) helpMenu.addAction(self.helpAction) self.qmenu = MenuWidget(self) self.toolBar2.addWidget(self.qmenu) # labels self.queue_panel_show_button.setText(QCoreApplication.translate("mainwindow_ui_tr", "Hide options")) self.start_checkBox.setText(QCoreApplication.translate("mainwindow_ui_tr", "Start Time")) self.end_checkBox.setText(QCoreApplication.translate("mainwindow_ui_tr", "End Time")) self.reverse_checkBox.setText(QCoreApplication.translate("mainwindow_ui_tr", "Download bottom of\n the list first")) self.limit_checkBox.setText(QCoreApplication.translate("mainwindow_ui_tr", "Limit Speed")) self.limit_comboBox.setItemText(0, "KiB/s") self.limit_comboBox.setItemText(1, "MiB/s") self.limit_pushButton.setText(QCoreApplication.translate("mainwindow_ui_tr", "Apply")) self.after_checkBox.setText(QCoreApplication.translate("mainwindow_ui_tr", "After download")) self.after_comboBox.setItemText(0, QCoreApplication.translate("mainwindow_ui_tr", "Shut Down")) self.keep_awake_checkBox.setText(QCoreApplication.translate("mainwindow_ui_tr", "Keep system awake!")) self.keep_awake_checkBox.setToolTip( QCoreApplication.translate("mainwindow_ui_tr", "<html><head/><body><p>This option is preventing system from going to sleep.\ This is necessary if your power manager is suspending system automatically. </p></body></html>")) self.after_pushButton.setText(QCoreApplication.translate("mainwindow_ui_tr", "Apply")) def changeIcon(self, icons): icons = ':/' + str(icons) + '/' action_icon_dict = {self.stopAllAction: 'stop_all', self.minimizeAction: 'minimize', self.addlinkAction: 'add', self.addtextfileAction: 'file', self.resumeAction: 'play', self.pauseAction: 'pause', self.stopAction: 'stop', self.propertiesAction: 'setting', self.progressAction: 'window', self.openFileAction: 'file', self.openDownloadFolderAction: 'folder', self.openDefaultDownloadFolderAction: 'folder', self.exitAction: 'exit', self.removeSelectedAction: 'multi_remove', self.deleteSelectedAction: 'multi_trash', self.createQueueAction: 'add_queue', self.removeQueueAction: 'remove_queue', self.startQueueAction: 'start_queue', self.stopQueueAction: 'stop_queue', self.preferencesAction: 'preferences', self.aboutAction: 'about', self.issueAction: 'about', self.updateAction: 'about', self.videoFinderAddLinkAction: 'video_finder', self.qmenu: 'menu'} for key in action_icon_dict.keys(): key.setIcon(QIcon(icons + str(action_icon_dict[key])))