def _setupUi(self): self.resize(400, 300) self.gridLayout = QGridLayout(self) self.label = QLabel(tr("Choose a type for this tab:")) self.label.setAlignment(Qt.AlignCenter) self.gridLayout.addWidget(self.label, 0, 0, 1, 3) self.gridLayout.addItem(horizontalSpacer(), 1, 0, 1, 1) self.verticalLayout = QVBoxLayout() BUTTONS = [ ('networthButton', tr("1. Net Worth"), 'balance_sheet_16'), ('profitButton', tr("2. Profit && Loss"), 'income_statement_16'), ('transactionButton', tr("3. Transactions"), 'transaction_table_16'), ('gledgerButton', tr("4. General Ledger"), 'gledger_16'), ('scheduleButton', tr("5. Schedules"), 'schedules_16'), ('budgetButton', tr("6. Budgets"), 'budget_16'), ('docpropsButton', tr("7. Document Properties"), 'gledger_16'), ] for i, (name, label, icon) in enumerate(BUTTONS, start=1): button = QPushButton(label) if icon: button.setIcon(QIcon(QPixmap(':/{}'.format(icon)))) self.verticalLayout.addWidget(button) setattr(self, name, button) shortcut = QShortcut(self) shortcut.setKey(QKeySequence(str(i))) shortcut.setContext(Qt.WidgetShortcut) setattr(self, 'shortcut{}'.format(i), shortcut) self.gridLayout.addLayout(self.verticalLayout, 1, 1, 1, 1) self.gridLayout.addItem(horizontalSpacer(), 1, 2, 1, 1) self.gridLayout.addItem(verticalSpacer(), 2, 1, 1, 1)
def install_shortcuts(obj, actions, ide): short = resources.get_shortcut for action in actions: short_key = action.get("shortcut", None) action_data = action.get("action", None) connect = action.get("connect", None) if connect == "open_project_properties": print("\nregistrando ::open_project_properties; obj:", obj) shortcut = None item_ui = None func = None if connect: func = getattr(obj, connect, None) if short_key and not action_data: if isinstance(short_key, QKeySequence): shortcut = QShortcut(short_key, ide) else: shortcut = QShortcut(short(short_key), ide) shortcut.setContext(Qt.ApplicationShortcut) if isinstance(func, collections.Callable): shortcut.activated.connect(func) if action_data: is_menu = action_data.get('is_menu', False) if is_menu: item_ui = QMenu(action_data['text'], ide) else: item_ui = QAction(action_data['text'], ide) object_name = "%s.%s" % (obj.__class__.__name__, connect) item_ui.setObjectName(object_name) image_name = action_data.get('image', None) section = action_data.get('section', None) weight = action_data.get('weight', None) keysequence = action_data.get('keysequence', None) if image_name: if isinstance(image_name, int): icon = ide.style().standardIcon(image_name) item_ui.setIcon(icon) elif isinstance(image_name, str): icon = QIcon(":img/" + image_name) item_ui.setIcon(icon) if short_key and not is_menu: item_ui.setShortcut(short(short_key)) item_ui.setShortcutContext(Qt.ApplicationShortcut) elif keysequence and not is_menu: item_ui.setShortcut(short(keysequence)) item_ui.setShortcutContext(Qt.ApplicationShortcut) if isinstance(func, collections.Callable) and not is_menu: item_ui.triggered['bool'].connect(lambda s, f=func: f()) if section and section[0] is not None and weight: ide.register_menuitem(item_ui, section, weight) if image_name and not is_menu: ide.register_toolbar(item_ui, section, weight) if short_key and shortcut: ide.register_shortcut(short_key, shortcut, item_ui)
def __init__(self, parent=None): QWidget.__init__(self, parent) Ui_PlaylistsWidget.setupUi(self, self) self.view.doubleClicked.connect(self.playlistClicked) deletePlaylistShortcut = QShortcut(QKeySequence('Del'), self.view) deletePlaylistShortcut.setContext(Qt.WidgetShortcut) deletePlaylistShortcut.activated.connect(self.onDeletePlaylist)
def __init__(self, parent=None): QWidget.__init__(self, parent) Ui_LibraryWidget.setupUi(self, self) self.rescanButton.show() self.scanProgressBar.hide() self.libraryModel = LibraryModel() self.treeView.setModel(self.libraryModel) self.libraryModel.toggleRow.connect(self.onToggleRow) self.rescanButton.clicked.connect(self.rescanClicked) self.treeView.doubleClicked.connect(self.onTreeViewDoubleClicked) self.querySearchBox.textChanged.connect(self.onQueryChanged) self.clearSearchButton.clicked.connect(self.onQueryClear) # shortcuts releaseSearchboxShortcut = QShortcut(QKeySequence('Esc'), self.querySearchBox) releaseSearchboxShortcut.setContext(Qt.WidgetShortcut) releaseSearchboxShortcut.activated.connect(self.onReleaseSearchbox) scrollLibraryShortcut = QShortcut(QKeySequence(Qt.Key_Down), self.querySearchBox) scrollLibraryShortcut.setContext(Qt.WidgetShortcut) scrollLibraryShortcut.activated.connect(self.onScrollLibrary) activateTracksShortcut = QShortcut(QKeySequence(Qt.Key_Return), self.treeView) activateTracksShortcut.setContext(Qt.WidgetShortcut) activateTracksShortcut.activated.connect(self.onActivateTracks)
def __init__(self, fileBrowser): QTreeView.__init__(self, fileBrowser) self._fileBrowser = fileBrowser self.setAttribute(Qt.WA_MacShowFocusRect, False) self.setAttribute(Qt.WA_MacSmallSize) self.setContextMenuPolicy(Qt.ActionsContextMenu) self.setHeaderHidden(True) self.setUniformRowHeights(True) self.setTextElideMode(Qt.ElideMiddle) # dir model self._dirsModel = _FileSystemModel(self) self._dirsModel.setNameFilterDisables(False) self._dirsModel.setFilter(QDir.AllDirs | QDir.AllEntries | QDir.CaseSensitive | QDir.NoDotAndDotDot) # self._dirsModel.directoryLoaded.connect(self.setFocus) TODO don't have this signal in my Qt version # create proxy model self._filteredModel = FileBrowserFilteredModel(self) self._filteredModel.setSourceModel(self._dirsModel) self.setModel(self._filteredModel) if not sys.platform.startswith('win'): self._dirsModel.setRootPath("/") else: self._dirsModel.setRootPath('') # shortcut accessible only when self._tree has focus self._upShortcut = QShortcut(QKeySequence("BackSpace"), self) self._upShortcut.setContext(Qt.WidgetShortcut) self._upShortcut.activated.connect(self.moveUp) # shortcut accessible only when self._tree has focus self._homeShortcut = QShortcut(QKeySequence("`"), self) self._homeShortcut.setContext(Qt.WidgetShortcut) self._homeShortcut.activated.connect(self._goUserHomeDir) # shortcut accessible only when self._tree has focus self._homeShortcut = QShortcut(QKeySequence("."), self) self._homeShortcut.setContext(Qt.WidgetShortcut) self._homeShortcut.activated.connect(self._goCurrentDir) self.activated.connect(self._onActivated) self._fileActivated.connect(fileBrowser.fileActivated) # QDirModel loads item asynchronously, therefore we need timer for setting focus to the first item self._setFocusTimer = QTimer() self._setFocusTimer.timeout.connect(self._setFirstItemAsCurrent) self._setFocusTimer.setInterval(50) self._timerAttempts = 0
def __init__(self, mapDocument, tileset, parent = None): super().__init__(parent) self.mUi = Ui_EditTerrainDialog() self.mMapDocument = mapDocument self.mInitialUndoStackIndex = self.mMapDocument.undoStack().index() self.mTileset = tileset self.mUi.setupUi(self) self.setWindowFlags(self.windowFlags() & ~Qt.WindowContextHelpButtonHint) Utils.setThemeIcon(self.mUi.redo, "edit-redo") Utils.setThemeIcon(self.mUi.undo, "edit-undo") zoomable = Zoomable(self) zoomable.connectToComboBox(self.mUi.zoomComboBox) tilesetModel = TilesetModel(self.mTileset, self.mUi.tilesetView) mapDocument.tileTerrainChanged.connect(tilesetModel.tilesChanged) self.mUi.tilesetView.setEditTerrain(True) self.mUi.tilesetView.setMapDocument(mapDocument) self.mUi.tilesetView.setZoomable(zoomable) self.mUi.tilesetView.setModel(tilesetModel) self.mTerrainModel = mapDocument.terrainModel() rootIndex = self.mTerrainModel.index(tileset) self.mUi.terrainList.setMapDocument(mapDocument) self.mUi.terrainList.setModel(self.mTerrainModel) self.mUi.terrainList.setRootIndex(rootIndex) terrainListHeader = self.mUi.terrainList.header() terrainListHeader.setSectionResizeMode(0, QHeaderView.ResizeToContents) selectionModel = self.mUi.terrainList.selectionModel() selectionModel.currentRowChanged.connect(self.selectedTerrainChanged) if (self.mTerrainModel.rowCount(rootIndex) > 0): selectionModel.setCurrentIndex(self.mTerrainModel.index(0, 0, rootIndex), QItemSelectionModel.SelectCurrent | QItemSelectionModel.Rows) self.mUi.terrainList.setFocus() self.mUi.eraseTerrain.toggled.connect(self.eraseTerrainToggled) self.mUi.addTerrainTypeButton.clicked.connect(self.addTerrainType) self.mUi.removeTerrainTypeButton.clicked.connect(self.removeTerrainType) self.mUi.tilesetView.createNewTerrainSignal.connect(self.addTerrainType) self.mUi.tilesetView.terrainImageSelected.connect(self.setTerrainImage) undoStack = mapDocument.undoStack() undoStack.indexChanged.connect(self.updateUndoButton) undoStack.canRedoChanged.connect(self.mUi.redo.setEnabled) self.mUi.undo.clicked.connect(undoStack.undo) self.mUi.redo.clicked.connect(undoStack.redo) self.mUndoShortcut = QShortcut(QKeySequence.Undo, self) self.mRedoShortcut = QShortcut(QKeySequence.Redo, self) self.mUndoShortcut.activated.connect(undoStack.undo) self.mRedoShortcut.activated.connect(undoStack.redo) eraseShortcut = QShortcut(QKeySequence(self.tr("E")), self) eraseShortcut.activated.connect(self.mUi.eraseTerrain.toggle) self.updateUndoButton() Utils.restoreGeometry(self)
def setup_inspector(self): """ This code from http://agateau.com/2012/02/03/pyqtwebkit-experiments-part-2-debugging/ """ page = self.web_view.page() page.settings().setAttribute(QWebSettings.DeveloperExtrasEnabled, True) self.web_inspector = QWebInspector(self) self.web_inspector.setPage(page) shortcut = QShortcut(self) shortcut.setKey(Qt.Key_F12) shortcut.activated.connect(self.toggle_inspector) self.web_inspector.setVisible(False)
def __init__(self, parentObject, windowTitle, windowIcon=QIcon(), shortcut=None): QDockWidget.__init__(self, parentObject) self._showAction = None self.setObjectName(str(self.__class__)) self.setWindowTitle(windowTitle) self.setFeatures(self.features() & (~QDockWidget.DockWidgetFloatable)) if not windowIcon.isNull(): self.setWindowIcon(windowIcon) if shortcut is not None: self.showAction().setShortcut(shortcut) self._titleBar = _TitleBar(self) self.setTitleBarWidget(self._titleBar) if shortcut is not None: toolTip = "Move focus with <b>%s</b>,<br/>close with <b>Esc</b>" % shortcut else: toolTip = "Close with <b>Esc</b>" self._titleBar.setToolTip(toolTip) self._closeShortcut = QShortcut(QKeySequence("Esc"), self) self._closeShortcut.setContext(Qt.WidgetWithChildrenShortcut) self._closeShortcut.activated.connect(self._close)
def __init__(self, parent = None, url = '', width = None, height = None, isDialog = False): super(Window, self).__init__(parent if isDialog else None) self.assets = assets assets.windows.append(self) if width is None: width = assets.manifest['width'] if height is None: height = assets.manifest['height'] windowFlags = Qt.WindowTitleHint | \ Qt.WindowSystemMenuHint | \ Qt.WindowMinimizeButtonHint | \ Qt.WindowMaximizeButtonHint | \ Qt.WindowCloseButtonHint if isDialog: windowFlags |= Qt.Dialog else: windowFlags |= Qt.CustomizeWindowHint self.dragParams = {'type': 0, 'x': self.shadowWidth, 'y': self.shadowWidth, 'size': 5, 'draging': False} self.api = API(self) self.parent = parent self.resize(width, height) self.setMouseTracking(True) self.setWindowFlags(windowFlags) self.setAttribute(Qt.WA_QuitOnClose, True) self.setAttribute(Qt.WA_DeleteOnClose, True) self.setAttribute(Qt.WA_TranslucentBackground, True) self.setWindowTitle(assets.manifest['name']) self.setResizable(assets.manifest['resizable']) self.setFrameless(assets.manifest['frameless']) self.setWindowIcon(QIcon(assets.manifest['icon'])) self._win_id = self.winId().__int__() self.webView = WebView(self, url) self.verticalLayout.addWidget(self.webView) if assets.manifest['debug']: shortcut = QShortcut(self) shortcut.setKey(Qt.Key_F12) shortcut.activated.connect(self.showInspector) self._old_window_state = self.windowState() self._is_max_to_min = False self._maximizable = True self.setClosable(True)
def initPlaylist(self): """Initialize song playlist.""" self.playlistTable = QTableWidget() self.playlistTable.setSelectionBehavior(QAbstractItemView.SelectRows) self.playlistTable.setSelectionMode( QAbstractItemView.ExtendedSelection) self.playlistTable.setSortingEnabled(True) self.playlistTable.setTabKeyNavigation(False) self.playlistTable.setEditTriggers(QAbstractItemView.NoEditTriggers) self.playlistTable.setAlternatingRowColors(True) self.playlistTable.setVerticalScrollMode( QAbstractItemView.ScrollPerPixel) self.playlistTable.setHorizontalScrollMode( QAbstractItemView.ScrollPerPixel) self.playlistTable.itemDoubleClicked.connect(self.doubleClicked) self.doubleClicked = False self.lastPlayed = -1 self.currentPlaying = -1 delete = QShortcut( QKeySequence.Delete, self.playlistTable, self.deleteSongs) delete.setContext(Qt.WidgetShortcut) self.playlistTable.setColumnCount(4) self.playlistTable.setHorizontalHeaderLabels( ['Artist', 'Title', 'Album', 'Duration']) # False - ascending order, True - descending self.descendingOrder = [False] * 4 self.playlistTable.horizontalHeader().sectionClicked.connect( self.toSort) self.windows = [] names = [] for index in range(self.playlist.mediaCount()): names.append(self.playlist.media(index).canonicalUrl().path()) self.addClicked(names) self.grid.addWidget(self.playlistTable, 2, 0, 1, 4) self.grid.setRowStretch(2, 1)
def _setupUi(self): self.setWindowTitle(tr("Lookup")) self.resize(314, 331) self.verticalLayout = QVBoxLayout(self) self.searchEdit = SearchEdit(self) self.verticalLayout.addWidget(self.searchEdit) self.namesList = QListWidget(self) self.namesList.setEditTriggers(QAbstractItemView.NoEditTriggers) self.namesList.setSelectionBehavior(QAbstractItemView.SelectRows) self.namesList.setUniformItemSizes(True) self.namesList.setSelectionRectVisible(True) self.verticalLayout.addWidget(self.namesList) self.searchEdit.immediate = True self._shortcutUp = QShortcut(self.searchEdit) self._shortcutUp.setKey(QKeySequence(Qt.Key_Up)) self._shortcutUp.setContext(Qt.WidgetShortcut) self._shortcutDown = QShortcut(self.searchEdit) self._shortcutDown.setKey(QKeySequence(Qt.Key_Down)) self._shortcutDown.setContext(Qt.WidgetShortcut)
def _setupInspector(self): """ F12키를 누르면 "개발자 도구"가 노출됨 """ # webinspector self.settings().setAttribute(QWebSettings.DeveloperExtrasEnabled, True) self.webInspector = QWebInspector(self) self.webInspector.setPage(self.page()) # shortcut shortcut = QShortcut(self) shortcut.setContext(Qt.ApplicationShortcut) shortcut.setKey(Qt.Key_F12) shortcut.activated.connect(self._toggleInspector) # Devtools self.webInspector.setVisible(True) self.devTool = QDialog(self) self.devTool.setWindowTitle("Development Tool") self.devTool.resize(950, 400) layout = QGridLayout() layout.setContentsMargins(0,0,0,0) layout.addWidget(self.webInspector) self.devTool.setLayout(layout)
class Tree(QTreeView): """File system tree """ _fileActivated = pyqtSignal() def __init__(self, fileBrowser): QTreeView.__init__(self, fileBrowser) self._fileBrowser = fileBrowser self.setAttribute(Qt.WA_MacShowFocusRect, False) self.setAttribute(Qt.WA_MacSmallSize) self.setContextMenuPolicy(Qt.ActionsContextMenu) self.setHeaderHidden(True) self.setUniformRowHeights(True) self.setTextElideMode(Qt.ElideMiddle) # dir model self._dirsModel = _FileSystemModel(self) self._dirsModel.setNameFilterDisables(False) self._dirsModel.setFilter(QDir.AllDirs | QDir.AllEntries | QDir.CaseSensitive | QDir.NoDotAndDotDot) # self._dirsModel.directoryLoaded.connect(self.setFocus) TODO don't have this signal in my Qt version # create proxy model self._filteredModel = FileBrowserFilteredModel(self) self._filteredModel.setSourceModel(self._dirsModel) self.setModel(self._filteredModel) if not sys.platform.startswith('win'): self._dirsModel.setRootPath("/") else: self._dirsModel.setRootPath('') # shortcut accessible only when self._tree has focus self._upShortcut = QShortcut(QKeySequence("BackSpace"), self) self._upShortcut.setContext(Qt.WidgetShortcut) self._upShortcut.activated.connect(self.moveUp) # shortcut accessible only when self._tree has focus self._homeShortcut = QShortcut(QKeySequence("`"), self) self._homeShortcut.setContext(Qt.WidgetShortcut) self._homeShortcut.activated.connect(self._goUserHomeDir) # shortcut accessible only when self._tree has focus self._homeShortcut = QShortcut(QKeySequence("."), self) self._homeShortcut.setContext(Qt.WidgetShortcut) self._homeShortcut.activated.connect(self._goCurrentDir) self.activated.connect(self._onActivated) self._fileActivated.connect(fileBrowser.fileActivated) # QDirModel loads item asynchronously, therefore we need timer for setting focus to the first item self._setFocusTimer = QTimer() self._setFocusTimer.timeout.connect(self._setFirstItemAsCurrent) self._setFocusTimer.setInterval(50) self._timerAttempts = 0 def term(self): self._setFocusTimer.stop() def _onActivated(self, idx): """File or directory doubleClicked """ index = self._filteredModel.mapToSource(idx) path = self._dirsModel.filePath(index) if os.path.isdir(path): self._fileBrowser.setCurrentPath(path) else: self._fileActivated.emit() core.workspace().openFile(path) core.workspace().focusCurrentDocument() def moveUp(self): """User pressed Up key or button. Move focus and root up """ current = self.currentIndex() if not current.isValid(): current = self.rootIndex().child(0, 0) self.setCurrentIndex(current) if current.parent() == self.rootIndex() or \ current == self.rootIndex(): # need to move root up if self.rootIndex().parent().isValid(): # not reached root of the FS tree newRoot = self.rootIndex().parent() parentPath = self._filteredModelIndexToPath(current.parent()) self._fileBrowser.setCurrentPath(self._filteredModelIndexToPath(newRoot)) self.collapseAll() # if moving root up - collapse all items parentIndex = self._filteredModel.mapFromSource(self._dirsModel.index(parentPath)) self._setCurrentItem(parentIndex) else: # need to move selection up parentOfCurrent = self.currentIndex().parent() self._setCurrentItem(parentOfCurrent) # move selection up def _goUserHomeDir(self): """Go to home directory """ self._fileBrowser.setCurrentPath(os.path.expanduser("~")) self.collapseAll() def _goCurrentDir(self): """Go to current directory """ self._fileBrowser.setCurrentPath(_getCurDir()) self.collapseAll() def _filteredModelIndexToPath(self, index): """Map index to file path """ srcIndex = self._filteredModel.mapToSource(index) return self._dirsModel.filePath(srcIndex) def currentPath(self): """Get current path (root of the tree) """ index = self.rootIndex() index = self._filteredModel.mapToSource(index) return self._dirsModel.filePath(index) def _isDescendant(self, child, parent): """Check if child is descendant of parent """ while child.isValid(): if child.parent() == parent: return True child = child.parent() return False def _setFirstItemAsCurrent(self): """QDirModel loads items asynchronously. Therefore we select current item by timer """ if not self.currentIndex().isValid() or \ not self._isDescendant(self.currentIndex(), self.rootIndex()): firstChild = self.rootIndex().child(0, 0) if firstChild.isValid(): self._setFocusTimer.stop() self._setCurrentItem(self.rootIndex().child(0, 0)) else: self._timerAttempts -= 1 if not self._timerAttempts: self._setFocusTimer.stop() else: # nothing to do, have focus self._setFocusTimer.stop() def setCurrentPath(self, path): """Set current path (root of the tree) """ # get index index = self._dirsModel.index(path) # set current path self._filteredModel.invalidate() newRoot = self._filteredModel.mapFromSource(index) self.setRootIndex(newRoot) self._timerAttempts = 10 self._setFocusTimer.start() def _setCurrentItem(self, index): """Make the item current and select it """ self.setCurrentIndex(index) self.selectionModel().select(index, QItemSelectionModel.SelectCurrent)
def __init__(self, parent=None): # pylint: disable=too-many-statements super(WatchpointsWidget, self).__init__(parent=parent) self._app_window = parent if self._app_window.dwarf is None: print('WatchpointsWidget created before Dwarf exists') return self._uppercase_hex = True self.setAutoFillBackground(True) # connect to dwarf self._app_window.dwarf.onWatchpointAdded.connect(self._on_watchpoint_added) self._app_window.dwarf.onWatchpointRemoved.connect( self._on_watchpoint_removed) # setup our model self._watchpoints_model = QStandardItemModel(0, 5) self._watchpoints_model.setHeaderData(0, Qt.Horizontal, 'Address') self._watchpoints_model.setHeaderData(1, Qt.Horizontal, 'R') self._watchpoints_model.setHeaderData(1, Qt.Horizontal, Qt.AlignCenter, Qt.TextAlignmentRole) self._watchpoints_model.setHeaderData(2, Qt.Horizontal, 'W') self._watchpoints_model.setHeaderData(2, Qt.Horizontal, Qt.AlignCenter, Qt.TextAlignmentRole) self._watchpoints_model.setHeaderData(3, Qt.Horizontal, 'X') self._watchpoints_model.setHeaderData(3, Qt.Horizontal, Qt.AlignCenter, Qt.TextAlignmentRole) self._watchpoints_model.setHeaderData(4, Qt.Horizontal, 'S') self._watchpoints_model.setHeaderData(4, Qt.Horizontal, Qt.AlignCenter, Qt.TextAlignmentRole) # setup ui v_box = QVBoxLayout(self) v_box.setContentsMargins(0, 0, 0, 0) self.list_view = DwarfListView() self.list_view.setModel(self._watchpoints_model) self.list_view.header().setSectionResizeMode(0, QHeaderView.Stretch) self.list_view.header().setSectionResizeMode( 1, QHeaderView.ResizeToContents | QHeaderView.Fixed) self.list_view.header().setSectionResizeMode( 2, QHeaderView.ResizeToContents | QHeaderView.Fixed) self.list_view.header().setSectionResizeMode( 3, QHeaderView.ResizeToContents | QHeaderView.Fixed) self.list_view.header().setSectionResizeMode( 4, QHeaderView.ResizeToContents | QHeaderView.Fixed) self.list_view.header().setStretchLastSection(False) self.list_view.doubleClicked.connect(self._on_item_dblclick) self.list_view.setContextMenuPolicy(Qt.CustomContextMenu) self.list_view.customContextMenuRequested.connect(self._on_contextmenu) v_box.addWidget(self.list_view) #header = QHeaderView(Qt.Horizontal, self) h_box = QHBoxLayout() h_box.setContentsMargins(5, 2, 5, 5) btn1 = QPushButton( QIcon(utils.resource_path('assets/icons/plus.svg')), '') btn1.setFixedSize(20, 20) btn1.clicked.connect(self._on_additem_clicked) btn2 = QPushButton( QIcon(utils.resource_path('assets/icons/dash.svg')), '') btn2.setFixedSize(20, 20) btn2.clicked.connect(self.delete_items) btn3 = QPushButton( QIcon(utils.resource_path('assets/icons/trashcan.svg')), '') btn3.setFixedSize(20, 20) btn3.clicked.connect(self.clear_list) h_box.addWidget(btn1) h_box.addWidget(btn2) h_box.addSpacerItem( QSpacerItem(0, 0, QSizePolicy.Expanding, QSizePolicy.Preferred)) h_box.addWidget(btn3) # header.setLayout(h_box) # header.setFixedHeight(25) # v_box.addWidget(header) v_box.addLayout(h_box) # create a centered dot icon _section_width = self.list_view.header().sectionSize(2) self._new_pixmap = QPixmap(_section_width, 20) self._new_pixmap.fill(Qt.transparent) painter = QPainter(self._new_pixmap) rect = QRect((_section_width * 0.5), 0, 20, 20) painter.setBrush(QColor('#666')) painter.setPen(QColor('#666')) painter.drawEllipse(rect) self._dot_icon = QIcon(self._new_pixmap) # shortcuts shortcut_add = QShortcut( QKeySequence(Qt.CTRL + Qt.Key_W), self._app_window, self._on_additem_clicked) shortcut_add.setAutoRepeat(False) self.setLayout(v_box)
def __init__(self, aPath, parent=None): super(VideoPlayer, self).__init__(parent) self.setAttribute(Qt.WA_NoSystemBackground, True) self.setAcceptDrops(True) self.mediaPlayer = QMediaPlayer(None, QMediaPlayer.StreamPlayback) self.mediaPlayer.mediaStatusChanged.connect(self.printMediaData) self.mediaPlayer.setVolume(80) self.videoWidget = QVideoWidget(self) self.lbl = QLineEdit('00:00:00') self.lbl.setReadOnly(True) self.lbl.setFixedWidth(70) self.lbl.setUpdatesEnabled(True) self.lbl.setStyleSheet(stylesheet(self)) self.elbl = QLineEdit('00:00:00') self.elbl.setReadOnly(True) self.elbl.setFixedWidth(70) self.elbl.setUpdatesEnabled(True) self.elbl.setStyleSheet(stylesheet(self)) self.playButton = QPushButton() self.playButton.setEnabled(False) self.playButton.setFixedWidth(32) self.playButton.setStyleSheet("background-color: black") self.playButton.setIcon(self.style().standardIcon(QStyle.SP_MediaPlay)) self.playButton.clicked.connect(self.play) self.positionSlider = QSlider(Qt.Horizontal, self) self.positionSlider.setStyleSheet(stylesheet(self)) self.positionSlider.setRange(0, 100) self.positionSlider.sliderMoved.connect(self.setPosition) self.positionSlider.sliderMoved.connect(self.handleLabel) self.positionSlider.setSingleStep(2) self.positionSlider.setPageStep(20) self.positionSlider.setAttribute(Qt.WA_TranslucentBackground, True) self.clip = QApplication.clipboard() self.process = QProcess(self) self.process.readyRead.connect(self.dataReady) # self.process.started.connect(lambda: print("grabbing YouTube URL")) self.process.finished.connect(self.playFromURL) self.myurl = "" controlLayout = QHBoxLayout() controlLayout.setContentsMargins(5, 0, 5, 0) controlLayout.addWidget(self.playButton) controlLayout.addWidget(self.lbl) controlLayout.addWidget(self.positionSlider) controlLayout.addWidget(self.elbl) layout = QVBoxLayout() layout.setContentsMargins(0, 0, 0, 0) layout.addWidget(self.videoWidget) layout.addLayout(controlLayout) self.setLayout(layout) self.myinfo = "©2016\nAxel Schneider\n\nMouse Wheel = Zoom\nUP = Volume Up\nDOWN = Volume Down\n" + \ "LEFT = < 1 Minute\nRIGHT = > 1 Minute\n" + \ "SHIFT+LEFT = < 10 Minutes\nSHIFT+RIGHT = > 10 Minutes" self.widescreen = True #### shortcuts #### self.shortcut = QShortcut(QKeySequence("q"), self) self.shortcut.activated.connect(self.handleQuit) self.shortcut = QShortcut(QKeySequence("u"), self) self.shortcut.activated.connect(self.playFromURL) self.shortcut = QShortcut(QKeySequence("y"), self) self.shortcut.activated.connect(self.getYTUrl) self.shortcut = QShortcut(QKeySequence("o"), self) self.shortcut.activated.connect(self.openFile) self.shortcut = QShortcut(QKeySequence(" "), self) self.shortcut.activated.connect(self.play) self.shortcut = QShortcut(QKeySequence("f"), self) self.shortcut.activated.connect(self.handleFullscreen) self.shortcut = QShortcut(QKeySequence("i"), self) self.shortcut.activated.connect(self.handleInfo) self.shortcut = QShortcut(QKeySequence("s"), self) self.shortcut.activated.connect(self.toggleSlider) self.shortcut = QShortcut(QKeySequence(Qt.Key_Right), self) self.shortcut.activated.connect(self.forwardSlider) self.shortcut = QShortcut(QKeySequence(Qt.Key_Left), self) self.shortcut.activated.connect(self.backSlider) self.shortcut = QShortcut(QKeySequence(Qt.Key_Up), self) self.shortcut.activated.connect(self.volumeUp) self.shortcut = QShortcut(QKeySequence(Qt.Key_Down), self) self.shortcut.activated.connect(self.volumeDown) self.shortcut = QShortcut( QKeySequence(Qt.ShiftModifier + Qt.Key_Right), self) self.shortcut.activated.connect(self.forwardSlider10) self.shortcut = QShortcut(QKeySequence(Qt.ShiftModifier + Qt.Key_Left), self) self.shortcut.activated.connect(self.backSlider10) self.mediaPlayer.setVideoOutput(self.videoWidget) self.mediaPlayer.stateChanged.connect(self.mediaStateChanged) self.mediaPlayer.positionChanged.connect(self.positionChanged) self.mediaPlayer.positionChanged.connect(self.handleLabel) self.mediaPlayer.durationChanged.connect(self.durationChanged) self.mediaPlayer.error.connect(self.handleError) print("QT5 Player started") self.suspend_screensaver() # msg = QMessageBox.information(self, "Qt5Player", "press o to open file") self.loadFilm("/home/brian/Dokumente/Qt5PlayerIntro.m4v")
elif reply == QMessageBox.Retry: color_pallet() return None # Определение позиции камеры camera_position = define_camera_place() # Привязка нижней панели кнопок к функция interface.buttonExit.clicked.connect(interface.close) interface.homeButton.clicked.connect(set_home_position) interface.cameraButton.clicked.connect(set_camera_position) interface.runButton.clicked.connect(getting_started) # Непосредственное управление роботом QShortcut(QKeySequence("W"), interface).activated.connect(lambda: interface.keyboardControl('W')) QShortcut(QKeySequence("A"), interface).activated.connect(lambda: interface.keyboardControl('A')) QShortcut(QKeySequence("S"), interface).activated.connect(lambda: interface.keyboardControl('S')) QShortcut(QKeySequence("D"), interface).activated.connect(lambda: interface.keyboardControl('D')) QShortcut( QKeySequence("Space"), interface).activated.connect(lambda: interface.keyboardControl('Space')) QShortcut(QKeySequence("C"), interface).activated.connect(lambda: interface.keyboardControl('C')) QShortcut(QKeySequence("Q"), interface).activated.connect(lambda: interface.keyboardControl('Q')) QShortcut(QKeySequence("E"), interface).activated.connect(lambda: interface.keyboardControl('E'))
def _setupUi(self): self.setWindowTitle(tr("Transaction Info")) self.resize(462, 329) self.setModal(True) self.mainLayout = QVBoxLayout(self) self.tabWidget = QTabWidget(self) self.infoTab = QWidget() self.infoLayout = QVBoxLayout(self.infoTab) self.formLayout = QFormLayout() self.formLayout.setFieldGrowthPolicy(QFormLayout.ExpandingFieldsGrow) self.dateEdit = DateEdit(self.infoTab) self.dateEdit.setMaximumSize(QSize(120, 16777215)) self.formLayout.addRow(tr("Date:"), self.dateEdit) self.descriptionEdit = DescriptionEdit(self.model.completable_edit, self.infoTab) self.formLayout.addRow(tr("Description:"), self.descriptionEdit) self.payeeEdit = PayeeEdit(self.model.completable_edit, self.infoTab) self.formLayout.addRow(tr("Payee:"), self.payeeEdit) self.checkNoEdit = QLineEdit(self.infoTab) self.checkNoEdit.setMaximumSize(QSize(120, 16777215)) self.formLayout.addRow(tr("Check #:"), self.checkNoEdit) self.infoLayout.addLayout(self.formLayout) self.amountLabel = QLabel(tr("Transfers:"), self.infoTab) self.infoLayout.addWidget(self.amountLabel) self.splitTableView = TableView(self.infoTab) self.splitTableView.setAcceptDrops(True) self.splitTableView.setEditTriggers(QAbstractItemView.DoubleClicked | QAbstractItemView.EditKeyPressed) self.splitTableView.setDragEnabled(True) self.splitTableView.setDragDropMode(QAbstractItemView.InternalMove) self.splitTableView.setSelectionMode(QAbstractItemView.SingleSelection) self.splitTableView.setSelectionBehavior(QAbstractItemView.SelectRows) self.splitTableView.horizontalHeader().setDefaultSectionSize(40) self.splitTableView.verticalHeader().setVisible(False) self.splitTableView.verticalHeader().setDefaultSectionSize(18) self.tvShortcut = QShortcut(QKeySequence("Alt+T"), self) self.tvShortcut.activated.connect(self.on_focus_transactions) self.infoLayout.addWidget(self.splitTableView) self.mctButtonsLayout = QHBoxLayout() self.mctButtonsLayout.setContentsMargins(0, 0, 0, 0) spacerItem = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum) self.mctButtonsLayout.addItem(spacerItem) self.mctButton = QPushButton(tr("&Multi-currency balance"), self.infoTab) self.mctButtonsLayout.addWidget(self.mctButton) self.assignImbalanceButton = QPushButton(tr("Assign &imbalance"), self.infoTab) self.mctButtonsLayout.addWidget(self.assignImbalanceButton) self.addSplitButton = QPushButton(self.infoTab) icon = QIcon() icon.addPixmap(QPixmap(":/plus_8"), QIcon.Normal, QIcon.Off) self.addSplitButton.setIcon(icon) self.mctButtonsLayout.addWidget(self.addSplitButton) self.removeSplitButton = QPushButton(self.infoTab) icon1 = QIcon() icon1.addPixmap(QPixmap(":/minus_8"), QIcon.Normal, QIcon.Off) self.removeSplitButton.setIcon(icon1) self.mctButtonsLayout.addWidget(self.removeSplitButton) self.infoLayout.addLayout(self.mctButtonsLayout) self.tabWidget.addTab(self.infoTab, tr("Info")) self.notesTab = QWidget() self.notesLayout = QVBoxLayout(self.notesTab) self.notesEdit = QPlainTextEdit(self.notesTab) self.notesLayout.addWidget(self.notesEdit) self.tabWidget.addTab(self.notesTab, tr("Notes")) self.tabWidget.setCurrentIndex(0) self.mainLayout.addWidget(self.tabWidget) self.buttonBox = QDialogButtonBox(self) self.buttonBox.setOrientation(Qt.Horizontal) self.buttonBox.addButton(tr("&Save"), QDialogButtonBox.AcceptRole) self.buttonBox.addButton(tr("Cancel"), QDialogButtonBox.RejectRole) self.mainLayout.addWidget(self.buttonBox)
def __init__(self, parent=None): super().__init__(parent) # load config self.data = yaml_loader() # load ui self.setupUi(self) # load icons self.setWindowTitle("Sputofy") self.setWindowIcon(QIcon(os.path.join(RES_PATH, "logo.svg"))) loopIcon = QIcon() loopIcon.addPixmap(QPixmap(os.path.join(RES_PATH, "loopIconOFF.svg"))) self.loopBtn.setIcon(loopIcon) prevIcon = QIcon() prevIcon.addPixmap(QPixmap(os.path.join(RES_PATH, "backwardIcon.svg"))) self.prevBtn.setIcon(prevIcon) playIcon = QIcon() playIcon.addPixmap(QPixmap(os.path.join(RES_PATH, "playIcon.svg"))) self.playBtn.setIcon(playIcon) nextIcon = QIcon() nextIcon.addPixmap(QPixmap(os.path.join(RES_PATH, "forwardIcon.svg"))) self.nextBtn.setIcon(nextIcon) randomIcon = QIcon() randomIcon.addPixmap( QPixmap(os.path.join(RES_PATH, "randomIconOFF.svg"))) self.randomBtn.setIcon(randomIcon) volumeIcon = QIcon() volumeIcon.addPixmap(QPixmap(os.path.join(RES_PATH, "volumeIcon.svg"))) self.volumeBtn.setIcon(volumeIcon) # window's settings self.xCor = self.data['last_position']['xPos'] self.yCor = self.data['last_position']['yPos'] self.widthSize = self.data['last_window_size']['width'] self.heightSize = self.data['last_window_size']['height'] self.setGeometry(self.xCor, self.yCor, self.widthSize, self.heightSize) # load YouTubeToMP3 self.YouTubeToMP3 = YouTubeToMP3Window() # open YouTubeToMP3 using button self.actionYT_MP3.triggered.connect(self.YouTubeToMP3.show_window) # info action self.actionInfo.triggered.connect(self.info_handle) #=========================== mediaplayer ============================== # create media player object self.mediaPlayer = QMediaPlayer(None) # open button self.actionOpen_Song.triggered.connect(self.open_song) self.actionOpen_Folder.triggered.connect(self.open_folder) # play button self.playBtn.setEnabled(False) self.playBtn.clicked.connect( self.play_video ) # when btn is pressed: if it is playing it pause, if it is paused it plays # QShortcut(QKeySequence("Space"), self).activated.connect(self.play_video)metodo da ricordare in caso di problemi #TODO # duration slider self.durationSlider.setEnabled(False) self.durationSliderMaxValue = 0 self.durationSlider.valueChanged.connect( self.mediaPlayer.setPosition ) # set mediaPlayer position using the value took from the slider QShortcut('Right', self, lambda: self.durationSlider.setValue( self.durationSlider.value() + 10000)) # 1s = 1000ms QShortcut('Left', self, lambda: self.durationSlider.setValue( self.durationSlider.value() - 10000)) # 1s = 1000ms QShortcut('Shift+Right', self, lambda: self.durationSlider.setValue( self.durationSliderMaxValue - 1000)) # jump to the end-1s of song QShortcut('Shift+Left', self, lambda: self.durationSlider.setValue(0)) # restart song # volumeSlider self.volumeSlider.setProperty("value", 100) self.volumeSlider.setRange(0, 100) self.volumeSlider.setValue( self.data['volume'] if self.data['volume'] != 0 else self.data['volume'] + 1 ) # set slider value | if saved volume is equal to 0 load with volume = 1 else load the saved volume self.mediaPlayer.setVolume( self.data['volume'] if self.data['volume'] != 0 else self.data['volume'] + 1 ) # set mediaPlayer volume | if saved volume is equal to 0 load with volume = 1 else load the saved volume self.volumeLabel.setText( f"{self.data['volume']}%" if self.data['volume'] != 0 else f"{self.data['volume']+1}%" ) # set volume label text | if saved volume is equal to 0 load with volume = 1 else load the saved volume self.volumeSlider.valueChanged.connect( self.mediaPlayer.setVolume ) # set mediaPlayer volume using the value took from the slider QShortcut('Up', self, lambda: self.volumeSlider.setValue( self.volumeSlider.value() + 1)) # volume + 1 QShortcut('Down', self, lambda: self.volumeSlider.setValue( self.volumeSlider.value() - 1)) # volume - 1 QShortcut( 'Shift+Up', self, lambda: self.volumeSlider.setValue(100)) # set maximum volume QShortcut( 'Shift+Down', self, lambda: self.volumeSlider.setValue(0)) # set minimun volume(mute) # volumeBtn self.volumeBtn.clicked.connect( self.volume_toggle) # mute/unmute volume pressing btn self.isMuted = False # starting with a non-muted volume self.previousVolume = self.data[ 'volume'] # loading last registered volume # media player signals self.mediaPlayer.durationChanged.connect( self.duration_changed) # set range of duration slider self.mediaPlayer.positionChanged.connect( self.position_changed) # duration slider progress self.mediaPlayer.stateChanged.connect( self.player_state) # see when it's playing or in pause self.mediaPlayer.volumeChanged.connect( self.volume_icon) # change volumebtn icon #=========================== playlist ============================== # create the playlist self.playlist = QMediaPlaylist() self.playlist.setPlaybackMode(2) self.mediaPlayer.setPlaylist(self.playlist) # clear the playlist self.playlistIsEmpty = True # playlistList model self.model = PlaylistModel(self.playlist) self.playlistView.setModel(self.model) self.playlist.currentIndexChanged.connect( self.playlist_position_changed) selection_model = self.playlistView.selectionModel() selection_model.selectionChanged.connect( self.playlist_selection_changed) #=========================== playlist function ============================== self.mediaList = [] # array of loaded songs self.currentPlaylist = "" # current loaded playlist name self.isCustomPlaylist = False # add song name on title self.playlist.currentMediaChanged.connect(self.set_title) # playlist buttons self.nextBtn.clicked.connect(self.next_song) # seek track forward self.prevBtn.clicked.connect(self.prev_song) # seek track backward self.mediaPlayer.mediaStatusChanged.connect( self.auto_next_track ) # once song is ended seek track forward and play it self.actionLoopIt.triggered.connect( self.loop_song) # (1) loop the same song self.actionShuffle.triggered.connect( self.shuffle_playlist) # change song's order self.loopBtn.clicked.connect(self.loop) # (3) loop the playlist self.randomBtn.clicked.connect( self.random) # (4) play random song without end # create new playlist self.actionCreatePlaylist.triggered.connect(self.custom_playlist) # delete current playlist self.actionDeletePlaylist.triggered.connect(self.delete_playlist) # remove all songs self.actionClearQueue.triggered.connect(self.clear_queue) # load playlist self.actionDict = {} # dictionary of action Objects for action in self.data['playlistList']: self.actionDict[action] = self.menuPlaylist.addAction( action, partial(self.load_playlist, action)) if len(self.data['playlistList']) == 0: self.menuPlaylist.menuAction().setVisible(False)
class _s_Actions(QObject): """This class is like the Sauron's Ring: One ring to rule them all, One ring to find them, One ring to bring them all and in the darkness bind them. This Class knows all the containers, and its know by all the containers, but the containers don't need to know between each other, in this way we can keep a better api without the need to tie the behaviour between the widgets, and let them just consume the 'actions' they need.""" fileExecuted = pyqtSignal(str) projectExecuted = pyqtSignal(str) def __init__(self): super(_s_Actions, self).__init__() #Definition Locator self._locator = locator.Locator() self.__codeBack = [] self.__codeForward = [] self.__bookmarksFile = '' self.__bookmarksPos = -1 self.__breakpointsFile = '' self.__breakpointsPos = -1 self.__operations = { 0: self._navigate_code_jumps, 1: self._navigate_bookmarks, 2: self._navigate_breakpoints} def install_shortcuts(self, ide): """Install the shortcuts to the IDE.""" self.ide = ide short = resources.get_shortcut self.shortChangeTab = QShortcut(short("Change-Tab"), self.ide) self.shortChangeTabReverse = QShortcut( short("Change-Tab-Reverse"), self.ide) self.shortMoveTabToRight = QShortcut( short("Move-Tab-to-right"), self.ide) self.shortMoveTabToLeft = QShortcut( short("Move-Tab-to-left"), self.ide) self.shortDuplicate = QShortcut(short("Duplicate"), self.ide) self.shortRemove = QShortcut(short("Remove-line"), self.ide) self.shortMoveUp = QShortcut(short("Move-up"), self.ide) self.shortMoveDown = QShortcut(short("Move-down"), self.ide) self.shortCloseTab = QShortcut(short("Close-tab"), self.ide) self.shortNew = QShortcut(short("New-file"), self.ide) self.shortNewProject = QShortcut(short("New-project"), self.ide) self.shortOpen = QShortcut(short("Open-file"), self.ide) self.shortOpenProject = QShortcut(short("Open-project"), self.ide) self.shortSave = QShortcut(short("Save-file"), self.ide) self.shortSaveProject = QShortcut(short("Save-project"), self.ide) self.shortPrint = QShortcut(short("Print-file"), self.ide) self.shortRedo = QShortcut(short("Redo"), self.ide) self.shortAddBookmark = QShortcut(short("Add-Bookmark-or-Breakpoint"), self.ide) self.shortComment = QShortcut(short("Comment"), self.ide) self.shortUncomment = QShortcut(short("Uncomment"), self.ide) self.shortHorizontalLine = QShortcut(short("Horizontal-line"), self.ide) self.shortTitleComment = QShortcut(short("Title-comment"), self.ide) self.shortIndentLess = QShortcut(short("Indent-less"), self.ide) self.shortHideMisc = QShortcut(short("Hide-misc"), self.ide) self.shortHideEditor = QShortcut(short("Hide-editor"), self.ide) self.shortHideExplorer = QShortcut(short("Hide-explorer"), self.ide) self.shortRunFile = QShortcut(short("Run-file"), self.ide) self.shortRunProject = QShortcut(short("Run-project"), self.ide) self.shortSwitchFocus = QShortcut(short("Switch-Focus"), self.ide) self.shortStopExecution = QShortcut(short("Stop-execution"), self.ide) self.shortHideAll = QShortcut(short("Hide-all"), self.ide) self.shortFullscreen = QShortcut(short("Full-screen"), self.ide) self.shortFind = QShortcut(short("Find"), self.ide) self.shortFindNext = QShortcut(short("Find-next"), self.ide) self.shortFindPrevious = QShortcut(short("Find-previous"), self.ide) self.shortFindReplace = QShortcut(short("Find-replace"), self.ide) self.shortFindWithWord = QShortcut(short("Find-with-word"), self.ide) self.shortHelp = QShortcut(short("Help"), self.ide) self.shortSplitHorizontal = QShortcut(short("Split-horizontal"), self.ide) self.shortSplitVertical = QShortcut(short("Split-vertical"), self.ide) self.shortFollowMode = QShortcut(short("Follow-mode"), self.ide) self.shortReloadFile = QShortcut(short("Reload-file"), self.ide) self.shortFindInFiles = QShortcut(short("Find-in-files"), self.ide) self.shortImport = QShortcut(short("Import"), self.ide) self.shortGoToDefinition = QShortcut(short("Go-to-definition"), self.ide) self.shortCompleteDeclarations = QShortcut( short("Complete-Declarations"), self.ide) self.shortCodeLocator = QShortcut(short("Code-locator"), self.ide) self.shortFileOpener = QShortcut(short("File-Opener"), self.ide) self.shortNavigateBack = QShortcut(short("Navigate-back"), self.ide) self.shortNavigateForward = QShortcut(short("Navigate-forward"), self.ide) self.shortOpenLastTabOpened = QShortcut(short("Open-recent-closed"), self.ide) self.shortShowCodeNav = QShortcut(short("Show-Code-Nav"), self.ide) self.shortShowPasteHistory = QShortcut(short("Show-Paste-History"), self.ide) self.shortPasteHistory = QShortcut(short("History-Paste"), self.ide) self.shortCopyHistory = QShortcut(short("History-Copy"), self.ide) self.shortHighlightWord = QShortcut(short("Highlight-Word"), self.ide) self.shortChangeSplitFocus = QShortcut(short("change-split-focus"), self.ide) self.shortMoveTabSplit = QShortcut(short("move-tab-to-next-split"), self.ide) self.shortChangeTabVisibility = QShortcut( short("change-tab-visibility"), self.ide) #Connect Shortcuts Signals self.shortNavigateBack.activated.connect(lambda: self.__navigate_with_keyboard(False)) self.shortNavigateForward.activated.connect(lambda: self.__navigate_with_keyboard(True)) self.shortCodeLocator.activated.connect(self.ide.status.show_locator) self.shortFileOpener.activated.connect(self.ide.status.show_file_opener) self.shortGoToDefinition.activated.connect(self.editor_go_to_definition) self.shortCompleteDeclarations.activated.connect(self.editor_complete_declaration) self.shortRedo.activated.connect(self.editor_redo) self.shortHorizontalLine.activated.connect(self.editor_insert_horizontal_line) self.shortTitleComment.activated.connect(self.editor_insert_title_comment) self.shortFollowMode.activated.connect(self.ide.mainContainer.show_follow_mode) self.shortReloadFile.activated.connect(self.ide.mainContainer.reload_file) self.shortSplitHorizontal.activated.connect(lambda: self.ide.mainContainer.split_tab(True)) self.shortSplitVertical.activated.connect(lambda: self.ide.mainContainer.split_tab(False)) self.shortNew.activated.connect(self.ide.mainContainer.add_editor) self.shortNewProject.activated.connect(self.ide.explorer.create_new_project) self.shortHideMisc.activated.connect(self.view_misc_visibility) self.shortHideEditor.activated.connect(self.view_main_visibility) self.shortHideExplorer.activated.connect(self.view_explorer_visibility) self.shortHideAll.activated.connect(self.hide_all) self.shortFullscreen.activated.connect(self.fullscreen_mode) self.shortOpen.activated.connect(self.ide.mainContainer.open_file) self.shortOpenProject.activated.connect(self.open_project) self.shortCloseTab.activated.connect(self.ide.mainContainer.close_tab) self.shortSave.activated.connect(self.ide.mainContainer.save_file) self.shortSaveProject.activated.connect(self.save_project) self.shortPrint.activated.connect(self.print_file) self.shortFind.activated.connect(self.ide.status.show) self.shortFindPrevious.activated.connect(self.ide.status._searchWidget.find_previous) self.shortFindNext.activated.connect(self.ide.status._searchWidget.find_next) self.shortFindWithWord.activated.connect(self.ide.status.show_with_word) self.shortFindReplace.activated.connect(self.ide.status.show_replace) self.shortRunFile.activated.connect(self.execute_file) self.shortRunProject.activated.connect(self.execute_project) self.shortSwitchFocus.activated.connect(self.switch_focus) self.shortStopExecution.activated.connect(self.kill_execution) self.shortIndentLess.activated.connect(self.editor_indent_less) self.shortComment.activated.connect(self.editor_comment) self.shortUncomment.activated.connect(self.editor_uncomment) self.shortHelp.activated.connect(self.ide.mainContainer.show_python_doc) self.shortImport.activated.connect(self.import_from_everywhere) self.shortFindInFiles.activated.connect(self.ide.misc.show_find_in_files_widget) self.shortMoveUp.activated.connect(self.editor_move_up) self.shortMoveDown.activated.connect(self.editor_move_down) self.shortRemove.activated.connect(self.editor_remove_line) self.shortDuplicate.activated.connect(self.editor_duplicate) self.shortOpenLastTabOpened.activated.connect(self.reopen_last_tab) self.shortChangeTab.activated.connect(self.ide.mainContainer.change_tab) self.shortChangeTabReverse.activated.connect(self.ide.mainContainer.change_tab_reverse) self.shortMoveTabToRight.activated.connect(self.move_tab) self.shortMoveTabToLeft.activated.connect(lambda: self.move_tab(next=False)) self.shortShowCodeNav.activated.connect(self.ide.mainContainer.show_navigation_buttons) self.shortAddBookmark.activated.connect(self._add_bookmark_breakpoint) self.shortShowPasteHistory.activated.connect(self.ide.central.lateralPanel.combo.showPopup) self.shortCopyHistory.activated.connect(self._copy_history) self.shortPasteHistory.activated.connect(self._paste_history) self.shortHighlightWord.activated.connect(self.editor_highlight_word) self.shortChangeSplitFocus.activated.connect(self.ide.mainContainer.change_split_focus) self.shortMoveTabSplit.activated.connect(self.move_tab_to_next_split) self.shortChangeTabVisibility.activated.connect(self.ide.mainContainer.change_tabs_visibility) key = Qt.Key_1 for i in range(10): if sys.platform == "darwin": short = TabShortcuts( QKeySequence(Qt.CTRL + Qt.ALT + key), self.ide, i) else: short = TabShortcuts(QKeySequence(Qt.ALT + key), self.ide, i) key += 1 short.activated.connect(self._change_tab_index) short = TabShortcuts(QKeySequence(Qt.ALT + Qt.Key_0), self.ide, 10) short.activated.connect(self._change_tab_index) #Connect SIGNALs from other objects self.ide.mainContainer._tabMain.runFile.connect(self.execute_file) self.ide.mainContainer._tabSecondary.runFile.connect(self.execute_file) self.ide.mainContainer._tabMain.addToProject[str].connect(self._add_file_to_project) self.ide.mainContainer._tabSecondary.addToProject[str].connect(self._add_file_to_project) self.ide.mainContainer.openProject[str].connect(self.open_project) # Not Configurable Shortcuts self._shortEscStatus = QShortcut(QKeySequence(Qt.Key_Escape), self.ide.status) self._shortEscMisc = QShortcut(QKeySequence(Qt.Key_Escape), self.ide.misc) self._shortEscStatus.activated.connect(self.ide.status.hide_status) self._shortEscMisc.activated.connect(self.ide.misc.hide) def update_shortcuts(self): """If the user update the key binded to any shortcut, update them.""" resources.load_shortcuts() short = resources.get_shortcut self.shortDuplicate.setKey(short("Duplicate")) self.shortRemove.setKey(short("Remove-line")) self.shortMoveUp.setKey(short("Move-up")) self.shortMoveDown.setKey(short("Move-down")) self.shortCloseTab.setKey(short("Close-tab")) self.shortNew.setKey(short("New-file")) self.shortNewProject.setKey(short("New-project")) self.shortOpen.setKey(short("Open-file")) self.shortOpenProject.setKey(short("Open-project")) self.shortSave.setKey(short("Save-file")) self.shortSaveProject.setKey(short("Save-project")) self.shortPrint.setKey(short("Print-file")) self.shortRedo.setKey(short("Redo")) self.shortComment.setKey(short("Comment")) self.shortUncomment.setKey(short("Uncomment")) self.shortHorizontalLine.setKey(short("Horizontal-line")) self.shortTitleComment.setKey(short("Title-comment")) self.shortIndentLess.setKey(short("Indent-less")) self.shortHideMisc.setKey(short("Hide-misc")) self.shortHideEditor.setKey(short("Hide-editor")) self.shortHideExplorer.setKey(short("Hide-explorer")) self.shortRunFile.setKey(short("Run-file")) self.shortRunProject.setKey(short("Run-project")) self.shortSwitchFocus.setKey(short("Switch-Focus")) self.shortStopExecution.setKey(short("Stop-execution")) self.shortHideAll.setKey(short("Hide-all")) self.shortFullscreen.setKey(short("Full-screen")) self.shortFind.setKey(short("Find")) self.shortFindNext.setKey(short("Find-next")) self.shortFindPrevious.setKey(short("Find-previous")) self.shortFindReplace.setKey(short("Find-replace")) self.shortFindWithWord.setKey(short("Find-with-word")) self.shortHelp.setKey(short("Help")) self.shortSplitHorizontal.setKey(short("Split-horizontal")) self.shortSplitVertical.setKey(short("Split-vertical")) self.shortFollowMode.setKey(short("Follow-mode")) self.shortReloadFile.setKey(short("Reload-file")) self.shortFindInFiles.setKey(short("Find-in-files")) self.shortImport.setKey(short("Import")) self.shortGoToDefinition.setKey(short("Go-to-definition")) self.shortCompleteDeclarations.setKey(short("Complete-Declarations")) self.shortCodeLocator.setKey(short("Code-locator")) self.shortFileOpener.setKey(short("File-Opener")) self.shortNavigateBack.setKey(short("Navigate-back")) self.shortNavigateForward.setKey(short("Navigate-forward")) self.shortOpenLastTabOpened.setKey(short("Open-recent-closed")) self.shortChangeTab.setKey(short("Change-Tab")) self.shortChangeTabReverse.setKey(short("Change-Tab-Reverse")) self.shortMoveTabToRight.setKey(short("Move-Tab-to-right")) self.shortMoveTabToLeft.setKey(short("Move-Tab-to-left")) self.shortAddBookmark.setKey(short("Add-Bookmark-or-Breakpoint")) self.shortShowCodeNav.setKey(short("Show-Code-Nav")) self.shortShowPasteHistory.setKey(short("Show-Paste-History")) self.shortPasteHistory.setKey(short("History-Paste")) self.shortCopyHistory.setKey(short("History-Copy")) self.shortHighlightWord.setKey(short("Highlight-Word")) self.shortChangeSplitFocus.setKey(short("change-split-focus")) self.shortMoveTabSplit.setKey(short("move-tab-to-next-split")) self.shortChangeTabVisibility.setKey(short("change-tab-visibility")) def move_tab_to_next_split(self): self.ide.mainContainer.move_tab_to_next_split( self.ide.mainContainer.actualTab) def switch_focus(self): widget = QApplication.focusWidget() if widget: if widget in (self.ide.mainContainer.actualTab, self.ide.mainContainer.actualTab.currentWidget()): self.ide.explorer.currentWidget().setFocus() elif widget in (self.ide.explorer, self.ide.explorer.currentWidget()): if self.ide.misc.isVisible(): self.ide.misc.stack.currentWidget().setFocus() else: self.ide.mainContainer.actualTab.currentWidget().setFocus() elif widget.parent() is self.ide.misc.stack: self.ide.mainContainer.actualTab.currentWidget().setFocus() def _change_tab_index(self): editorWidget = self.ide.mainContainer.get_actual_editor() if editorWidget and editorWidget.hasFocus(): container = self.ide.mainContainer.actualTab else: container = self.ide.explorer obj = self.sender() if obj.index < container.count(): container.setCurrentIndex(obj.index) def _copy_history(self): """Copy the selected text into the copy/paste history.""" editorWidget = self.ide.mainContainer.get_actual_editor() if editorWidget and editorWidget.hasFocus(): cursor = editorWidget.textCursor() copy = cursor.selectedText() self.ide.central.lateralPanel.add_new_copy(copy) def _paste_history(self): """Paste the text from the copy/paste history.""" editorWidget = self.ide.mainContainer.get_actual_editor() if editorWidget and editorWidget.hasFocus(): cursor = editorWidget.textCursor() paste = self.ide.central.lateralPanel.get_paste() cursor.insertText(paste) def _add_bookmark_breakpoint(self): """Add a bookmark or breakpoint to the current file in the editor.""" editorWidget = self.ide.mainContainer.get_actual_editor() if editorWidget and editorWidget.hasFocus(): if self.ide.mainContainer.actualTab.navigator.operation == 1: editorWidget._sidebarWidget.set_bookmark( editorWidget.textCursor().blockNumber()) elif self.ide.mainContainer.actualTab.navigator.operation == 2: editorWidget._sidebarWidget.set_breakpoint( editorWidget.textCursor().blockNumber()) def __navigate_with_keyboard(self, val): """Navigate between the positions in the jump history stack.""" op = self.ide.mainContainer._tabMain.navigator.operation self.navigate_code_history(val, op) def _add_file_to_project(self, path): """Add the file for 'path' in the project the user choose here.""" pathProject = [self.ide.explorer.get_actual_project()] addToProject = ui_tools.AddToProject(pathProject, self.ide) addToProject.exec_() if not addToProject.pathSelected: return editorWidget = self.ide.mainContainer.get_actual_editor() if not editorWidget.ID: name = QInputDialog.getText(None, _translate("_s_Actions", "Add File To Project"), _translate("_s_Actions", "File Name:"))[0] if not name: QMessageBox.information(None, _translate("_s_Actions", "Invalid Name"), _translate("_s_Actions", "The file name is empty, please enter a name")) return else: name = file_manager.get_basename(editorWidget.ID) path = file_manager.create_path(addToProject.pathSelected, name) try: path = file_manager.store_file_content( path, editorWidget.get_text(), newFile=True) self.ide.mainContainer._file_watcher.allow_kill = False if path != editorWidget.ID: self.ide.mainContainer.remove_standalone_watcher( editorWidget.ID) editorWidget.ID = path self.ide.mainContainer.add_standalone_watcher(path) self.ide.mainContainer._file_watcher.allow_kill = True self.ide.explorer.add_existing_file(path) self.ide.change_window_title(path) name = file_manager.get_basename(path) self.ide.mainContainer.actualTab.setTabText( self.ide.mainContainer.actualTab.currentIndex(), name) editorWidget._file_saved() except file_manager.NinjaFileExistsException as ex: QMessageBox.information(None, _translate("_s_Actions", "File Already Exists"), (_translate("_s_Actions", "Invalid Path: the file '%s' already exists.") % ex.filename)) def add_project_to_console(self, projectFolder): """Add the namespace of the project received into the ninja-console.""" self.ide.misc._console.load_project_into_console(projectFolder) def remove_project_from_console(self, projectFolder): """Remove the namespace of the project received from the console.""" self.ide.misc._console.unload_project_from_console(projectFolder) def import_from_everywhere(self): """Show the dialog to insert an import from any place in the editor.""" editorWidget = self.ide.mainContainer.get_actual_editor() if editorWidget: text = editorWidget.get_text() froms = re.findall('^from (.*)', text, re.MULTILINE) fromSection = list(set([f.split(' import')[0] for f in froms])) dialog = from_import_dialog.FromImportDialog(fromSection, editorWidget, self.ide) dialog.show() def open_project(self, path=''): """Open a Project and load the symbols in the Code Locator.""" self.ide.explorer.open_project_folder(path) def open_project_properties(self): """Open a Project and load the symbols in the Code Locator.""" self.ide.explorer.open_project_properties() def create_profile(self): """Create a profile binding files and projects to a key.""" profileInfo = QInputDialog.getText(None, _translate("_s_Actions", "Create Profile"), _translate("_s_Actions", "The Current Files and Projects will " "be associated to this profile.\n" "Profile Name:")) if profileInfo[1]: profileName = profileInfo[0] if not profileName or profileName in settings.PROFILES: QMessageBox.information(None, _translate("_s_Actions", "Profile Name Invalid"), _translate("_s_Actions", "The Profile name is invalid or already exists.")) return self.save_profile(profileName) return profileName def save_profile(self, profileName): """Save the updates from a profile.""" projects_obj = self.ide.explorer.get_opened_projects() projects = [p.path for p in projects_obj] files = self.ide.mainContainer.get_opened_documents() files = files[0] + files[1] settings.PROFILES[profileName] = [files, projects] qsettings = QSettings(resources.SETTINGS_PATH, QSettings.IniFormat) qsettings.setValue('ide/profiles', settings.PROFILES) def activate_profile(self): """Show the Profile Manager dialog.""" profilesLoader = ui_tools.ProfilesLoader(self._load_profile_data, self.create_profile, self.save_profile, settings.PROFILES, self.ide) profilesLoader.show() def deactivate_profile(self): """Close the Profile Session.""" self.ide.Profile = None def _load_profile_data(self, key): """Activate the selected profile, closing the current files/projects""" self.ide.explorer.close_opened_projects() self.ide.mainContainer.open_files(settings.PROFILES[key][0]) self.ide.explorer.open_session_projects(settings.PROFILES[key][1]) def close_files_from_project(self, project): """Close the files related to this project.""" if project: tabMain = self.ide.mainContainer._tabMain for tabIndex in reversed(list(range(tabMain.count()))): if file_manager.belongs_to_folder( project, tabMain.widget(tabIndex).ID): tabMain.removeTab(tabIndex) tabSecondary = self.ide.mainContainer._tabSecondary for tabIndex in reversed(list(range(tabSecondary.count()))): if file_manager.belongs_to_folder( project, tabSecondary.widget(tabIndex).ID): tabSecondary.removeTab(tabIndex) self.ide.profile = None def count_file_code_lines(self): """Count the lines of code in the current file.""" editorWidget = self.ide.mainContainer.get_actual_editor() if editorWidget: block_count = editorWidget.blockCount() blanks = re.findall('(^\n)|(^(\s+)?#)|(^( +)?($|\n))', editorWidget.get_text(), re.M) blanks_count = len(blanks) resume = _translate("_s_Actions", "Lines code: %s\n") % (block_count - blanks_count) resume += (_translate("_s_Actions", "Blanks and commented lines: %s\n\n") % blanks_count) resume += _translate("_s_Actions", "Total lines: %s") % block_count msgBox = QMessageBox(QMessageBox.Information, _translate("_s_Actions", "Summary of lines"), resume, QMessageBox.Ok, editorWidget) msgBox.exec_() def execute_file(self): """Execute the current file.""" editorWidget = self.ide.mainContainer.get_actual_editor() #emit a signal for plugin! if editorWidget: self.fileExecuted.emit(editorWidget.ID)# moved here. Reason: case editorWidget == None self.ide.mainContainer.save_file(editorWidget) ext = file_manager.get_file_extension(editorWidget.ID) #TODO: Remove the IF statment with polymorphism using Handler if ext == 'py': self.ide.misc.run_application(editorWidget.ID) elif ext == 'html': self.ide.misc.render_web_page(editorWidget.ID) def execute_project(self): """Execute the project marked as Main Project.""" mainFile = self.ide.explorer.get_project_main_file() if not mainFile and self.ide.explorer._treeProjects and \ self.ide.explorer._treeProjects._actualProject: self.ide.explorer._treeProjects.open_project_properties() elif mainFile: self.save_project() path = self.ide.explorer.get_actual_project() #emit a signal for plugin! self.projectExecuted.emit(path) # load our jutsus! project = json_manager.read_ninja_project(path) python_exec = project.get('venv', False) if not python_exec: python_exec = project.get('pythonPath', 'python') PYTHONPATH = project.get('PYTHONPATH', None) params = project.get('programParams', '') preExec = project.get('preExecScript', '') postExec = project.get('postExecScript', '') mainFile = file_manager.create_path(path, mainFile) self.ide.misc.run_application(mainFile, pythonPath=python_exec, PYTHONPATH=PYTHONPATH, programParams=params, preExec=preExec, postExec=postExec) def kill_execution(self): """Kill the execution of the current file or project.""" self.ide.misc.kill_application() def fullscreen_mode(self): """Change to fullscreen mode.""" if self.ide.isFullScreen(): self.ide.showMaximized() else: self.ide.showFullScreen() def editor_redo(self): """Execute the redo action in the current editor.""" editorWidget = self.ide.mainContainer.get_actual_editor() if editorWidget and editorWidget.hasFocus(): editorWidget.redo() def editor_indent_less(self): """Indent 1 position to the left for the current line or selection.""" editorWidget = self.ide.mainContainer.get_actual_editor() if editorWidget and editorWidget.hasFocus(): editorWidget.indent_less() def editor_indent_more(self): """Indent 1 position to the right for the current line or selection.""" editorWidget = self.ide.mainContainer.get_actual_editor() if editorWidget and editorWidget.hasFocus(): editorWidget.indent_more() def editor_insert_debugging_prints(self): """Insert a print statement in each selected line.""" editorWidget = self.ide.mainContainer.get_actual_editor() if editorWidget: helpers.insert_debugging_prints(editorWidget) def editor_insert_pdb(self): """Insert a pdb.set_trace() statement in tjhe current line.""" editorWidget = self.ide.mainContainer.get_actual_editor() if editorWidget: helpers.insert_pdb(editorWidget) def editor_comment(self): """Mark the current line or selection as a comment.""" editorWidget = self.ide.mainContainer.get_actual_editor() if editorWidget and editorWidget.hasFocus(): helpers.comment(editorWidget) def editor_uncomment(self): """Uncomment the current line or selection.""" editorWidget = self.ide.mainContainer.get_actual_editor() if editorWidget and editorWidget.hasFocus(): helpers.uncomment(editorWidget) def editor_insert_horizontal_line(self): """Insert an horizontal lines of comment symbols.""" editorWidget = self.ide.mainContainer.get_actual_editor() if editorWidget and editorWidget.hasFocus(): helpers.insert_horizontal_line(editorWidget) def editor_insert_title_comment(self): """Insert a Title surrounded by comment symbols.""" editorWidget = self.ide.mainContainer.get_actual_editor() if editorWidget and editorWidget.hasFocus(): helpers.insert_title_comment(editorWidget) def editor_remove_trailing_spaces(self): """Remove the trailing spaces in the current editor.""" editorWidget = self.ide.mainContainer.get_actual_editor() if editorWidget: helpers.remove_trailing_spaces(editorWidget) def editor_replace_tabs_with_spaces(self): """Replace the Tabs with Spaces in the current editor.""" editorWidget = self.ide.mainContainer.get_actual_editor() if editorWidget: helpers.replace_tabs_with_spaces(editorWidget) def editor_move_up(self): """Move the current line or selection one position up.""" editorWidget = self.ide.mainContainer.get_actual_editor() if editorWidget and editorWidget.hasFocus(): helpers.move_up(editorWidget) def editor_move_down(self): """Move the current line or selection one position down.""" editorWidget = self.ide.mainContainer.get_actual_editor() if editorWidget and editorWidget.hasFocus(): helpers.move_down(editorWidget) def editor_remove_line(self): """Remove the current line or selection.""" editorWidget = self.ide.mainContainer.get_actual_editor() if editorWidget and editorWidget.hasFocus(): helpers.remove_line(editorWidget) def editor_duplicate(self): """Duplicate the current line or selection.""" editorWidget = self.ide.mainContainer.get_actual_editor() if editorWidget and editorWidget.hasFocus(): helpers.duplicate(editorWidget) def editor_go_to_definition(self): """Search the definition of the method or variable under the cursor. If more than one method or variable is found with the same name, shows a table with the results and let the user decide where to go.""" editorWidget = self.ide.mainContainer.get_actual_editor() if editorWidget and editorWidget.hasFocus(): editorWidget.go_to_definition() def editor_highlight_word(self): """Highlight the occurrences of the current word in the editor.""" editorWidget = self.ide.mainContainer.get_actual_editor() if editorWidget and editorWidget.hasFocus(): editorWidget.highlight_selected_word() def editor_complete_declaration(self): """Do the opposite action that Complete Declaration expect.""" editorWidget = self.ide.mainContainer.get_actual_editor() if editorWidget and editorWidget.hasFocus(): editorWidget.complete_declaration() def editor_go_to_line(self, line): """Jump to the specified line in the current editor.""" editorWidget = self.ide.mainContainer.get_actual_editor() if editorWidget: editorWidget.jump_to_line(line) def reset_editor_flags(self): """Reset the Flags for all the opened editors.""" self.ide.mainContainer.reset_editor_flags() def call_editors_function(self, call_function, *args, **kwargs): self.ide.mainContainer.call_editors_function( call_function, args, kwargs) def preview_in_browser(self): """Load the current html file in the default browser.""" editorWidget = self.ide.mainContainer.get_actual_editor() if editorWidget: if not editorWidget.ID: self.ide.mainContainer.save_file() ext = file_manager.get_file_extension(editorWidget.ID) if ext == 'html': webbrowser.open(editorWidget.ID) def hide_all(self): """Hide/Show all the containers except the editor.""" if self.ide.menuBar().isVisible(): self.ide.central.lateralPanel.hide() self.ide.misc.hide() self.ide.toolbar.hide() self.ide.menuBar().hide() else: self.ide.central.lateralPanel.show() self.ide.toolbar.show() self.ide.menuBar().show() self.ide._menuView.hideAllAction.setChecked( self.ide.menuBar().isVisible()) self.ide._menuView.hideConsoleAction.setChecked( self.ide.central.misc.isVisible()) self.ide._menuView.hideEditorAction.setChecked( self.ide.central.mainContainer.isVisible()) self.ide._menuView.hideExplorerAction.setChecked( self.ide.central.lateralPanel.isVisible()) self.ide._menuView.hideToolbarAction.setChecked( self.ide.toolbar.isVisible()) def view_misc_visibility(self): self.ide.central.change_misc_visibility() self.ide._menuView.hideConsoleAction.setChecked( self.ide.central.misc.isVisible()) def view_main_visibility(self): self.ide.central.change_main_visibility() self.ide._menuView.hideEditorAction.setChecked( self.ide.central.mainContainer.isVisible()) def view_explorer_visibility(self): self.ide.central.change_explorer_visibility() self.ide._menuView.hideExplorerAction.setChecked( self.ide.central.lateralPanel.isVisible()) def save_project(self): """Save all the opened files that belongs to the actual project.""" path = self.ide.explorer.get_actual_project() if path: self.ide.mainContainer.save_project(path) def save_all(self): """Save all the opened files.""" self.ide.mainContainer.save_all() def print_file(self): """Call the print of ui_tool Call print of ui_tool depending on the focus of the application""" #TODO: Add funtionality for proyect tab and methods tab editorWidget = self.ide.mainContainer.get_actual_editor() if editorWidget is not None: fileName = "newDocument.pdf" if editorWidget.ID: fileName = file_manager.get_basename( editorWidget.ID) fileName = fileName[:fileName.rfind('.')] + '.pdf' ui_tools.print_file(fileName, editorWidget.print_) def locate_function(self, function, filePath, isVariable): """Move the cursor to the proper position in the navigate stack.""" editorWidget = self.ide.mainContainer.get_actual_editor() if editorWidget: self.__codeBack.append((editorWidget.ID, editorWidget.textCursor().position())) self.__codeForward = [] self._locator.navigate_to(function, filePath, isVariable) def update_explorer(self): """Update the symbols in the Symbol Explorer when a file is saved.""" editorWidget = self.ide.mainContainer.get_actual_editor() if editorWidget: ext = file_manager.get_file_extension(editorWidget.ID) #obtain a symbols handler for this file extension symbols_handler = settings.get_symbols_handler(ext) if symbols_handler: source = editorWidget.toPlainText() if editorWidget.encoding is not None: source = source.encode(editorWidget.encoding) if ext == 'py': args = (source, True) else: args = (source,) symbols = symbols_handler.obtain_symbols(*args) self.ide.explorer.update_symbols(symbols, editorWidget.ID) #TODO: Should we change the code below similar to the code above? exts = settings.SYNTAX.get('python')['extension'] if ext in exts or editorWidget.newDocument: self.ide.explorer.update_errors( editorWidget.errors, editorWidget.pep8) def update_migration_tips(self): """Update the migration tips in the Explorer.""" # This should be refactored with the new definition of singals in # the MainContainer editorWidget = self.ide.mainContainer.get_actual_editor() if editorWidget: self.ide.explorer.update_migration(editorWidget.migration) def navigate_code_history(self, val, op): """Navigate the code history.""" self.__operations[op](val) def _navigate_code_jumps(self, val): """Navigate between the jump points.""" node = None if not val and self.__codeBack: node = self.__codeBack.pop() editorWidget = self.ide.mainContainer.get_actual_editor() if editorWidget: self.__codeForward.append((editorWidget.ID, editorWidget.textCursor().position())) elif val and self.__codeForward: node = self.__codeForward.pop() editorWidget = self.ide.mainContainer.get_actual_editor() if editorWidget: self.__codeBack.append((editorWidget.ID, editorWidget.textCursor().position())) if node: self.ide.mainContainer.open_file(node[0], node[1]) def _navigate_breakpoints(self, val): """Navigate between the breakpoints.""" breakList = list(settings.BREAKPOINTS.keys()) breakList.sort() if not breakList: return if self.__breakpointsFile not in breakList: self.__breakpointsFile = breakList[0] index = breakList.index(self.__breakpointsFile) breaks = settings.BREAKPOINTS.get(self.__breakpointsFile, []) lineNumber = 0 #val == True: forward if val: if (len(breaks) - 1) > self.__breakpointsPos: self.__breakpointsPos += 1 lineNumber = breaks[self.__breakpointsPos] elif len(breaks) > 0: if index < (len(breakList) - 1): self.__breakpointsFile = breakList[index + 1] else: self.__breakpointsFile = breakList[0] self.__breakpointsPos = 0 breaks = settings.BREAKPOINTS[self.__breakpointsFile] lineNumber = breaks[0] else: if self.__breakpointsPos > 0: self.__breakpointsPos -= 1 lineNumber = breaks[self.__breakpointsPos] elif len(breaks) > 0: self.__breakpointsFile = breakList[index - 1] breaks = settings.BREAKPOINTS[self.__breakpointsFile] self.__breakpointsPos = len(breaks) - 1 lineNumber = breaks[self.__breakpointsPos] if file_manager.file_exists(self.__breakpointsFile): self.ide.mainContainer.open_file(self.__breakpointsFile, lineNumber, None, True) else: settings.BREAKPOINTS.pop(self.__breakpointsFile) def _navigate_bookmarks(self, val): """Navigate between the bookmarks.""" bookList = list(settings.BOOKMARKS.keys()) bookList.sort() if not bookList: return if self.__bookmarksFile not in bookList: self.__bookmarksFile = bookList[0] index = bookList.index(self.__bookmarksFile) bookms = settings.BOOKMARKS.get(self.__bookmarksFile, []) lineNumber = 0 #val == True: forward if val: if (len(bookms) - 1) > self.__bookmarksPos: self.__bookmarksPos += 1 lineNumber = bookms[self.__bookmarksPos] elif len(bookms) > 0: if index < (len(bookList) - 1): self.__bookmarksFile = bookList[index + 1] else: self.__bookmarksFile = bookList[0] self.__bookmarksPos = 0 bookms = settings.BOOKMARKS[self.__bookmarksFile] lineNumber = bookms[0] else: if self.__bookmarksPos > 0: self.__bookmarksPos -= 1 lineNumber = bookms[self.__bookmarksPos] elif len(bookms) > 0: self.__bookmarksFile = bookList[index - 1] bookms = settings.BOOKMARKS[self.__bookmarksFile] self.__bookmarksPos = len(bookms) - 1 lineNumber = bookms[self.__bookmarksPos] if file_manager.file_exists(self.__bookmarksFile): self.ide.mainContainer.open_file(self.__bookmarksFile, lineNumber, None, True) else: settings.BOOKMARKS.pop(self.__bookmarksFile) def add_back_item_navigation(self): """Add an item to the back stack and reset the forward stack.""" editorWidget = self.ide.mainContainer.get_actual_editor() if editorWidget: self.__codeBack.append((editorWidget.ID, editorWidget.textCursor().position())) self.__codeForward = [] def group_tabs_together(self): """Group files that belongs to the same project together.""" if self.ide.explorer._treeProjects is None: return projects_obj = self.ide.explorer.get_opened_projects() projects = [p.path for p in projects_obj] for project in projects: projectName = self.ide.explorer.get_project_name(project) if not projectName: projectName = file_manager.get_basename(project) tabGroup = tab_group.TabGroup(project, projectName, self) for index in reversed(list(range( self.ide.mainContainer._tabMain.count()))): widget = self.ide.mainContainer._tabMain.widget(index) if type(widget) is editor.Editor and \ file_manager.belongs_to_folder(project, widget.ID): tabGroup.add_widget(widget) self.ide.mainContainer._tabMain.removeTab(index) if tabGroup.tabs: self.ide.mainContainer._tabMain.add_tab(tabGroup, projectName) def deactivate_tabs_groups(self): """Deactivate tab grouping based in the project they belong.""" for index in reversed(list(range( self.ide.mainContainer._tabMain.count()))): widget = self.ide.mainContainer._tabMain.widget(index) if type(widget) is tab_group.TabGroup: widget.only_expand() def reopen_last_tab(self): """Reopen the last closed tab.""" self.ide.mainContainer.actualTab._reopen_last_tab() def open_class_diagram(self): """Open the Class Diagram Generator.""" diagram = class_diagram.ClassDiagram(self) self.ide.mainContainer.add_tab(diagram, _translate("_s_Actions", "Class Diagram v.0.1")) def reload_toolbar(self): """Reload the Toolbar.""" self.ide.load_toolbar() def move_tab(self, next=True, widget=None): actualTab = self.ide.mainContainer.actualTab if widget is None: widget = actualTab.currentWidget() if widget is not None: old_widget_index = actualTab.indexOf(widget) if next and old_widget_index < actualTab.count() - 1: new_widget_index = old_widget_index + 1 elif old_widget_index > 0 and not next: new_widget_index = old_widget_index - 1 else: return tabName = actualTab.tabText(old_widget_index) actualTab.insertTab(new_widget_index, widget, tabName) actualTab.setCurrentIndex(new_widget_index)
def install_shortcuts(self, ide): """Install the shortcuts to the IDE.""" self.ide = ide short = resources.get_shortcut self.shortChangeTab = QShortcut(short("Change-Tab"), self.ide) self.shortChangeTabReverse = QShortcut( short("Change-Tab-Reverse"), self.ide) self.shortMoveTabToRight = QShortcut( short("Move-Tab-to-right"), self.ide) self.shortMoveTabToLeft = QShortcut( short("Move-Tab-to-left"), self.ide) self.shortDuplicate = QShortcut(short("Duplicate"), self.ide) self.shortRemove = QShortcut(short("Remove-line"), self.ide) self.shortMoveUp = QShortcut(short("Move-up"), self.ide) self.shortMoveDown = QShortcut(short("Move-down"), self.ide) self.shortCloseTab = QShortcut(short("Close-tab"), self.ide) self.shortNew = QShortcut(short("New-file"), self.ide) self.shortNewProject = QShortcut(short("New-project"), self.ide) self.shortOpen = QShortcut(short("Open-file"), self.ide) self.shortOpenProject = QShortcut(short("Open-project"), self.ide) self.shortSave = QShortcut(short("Save-file"), self.ide) self.shortSaveProject = QShortcut(short("Save-project"), self.ide) self.shortPrint = QShortcut(short("Print-file"), self.ide) self.shortRedo = QShortcut(short("Redo"), self.ide) self.shortAddBookmark = QShortcut(short("Add-Bookmark-or-Breakpoint"), self.ide) self.shortComment = QShortcut(short("Comment"), self.ide) self.shortUncomment = QShortcut(short("Uncomment"), self.ide) self.shortHorizontalLine = QShortcut(short("Horizontal-line"), self.ide) self.shortTitleComment = QShortcut(short("Title-comment"), self.ide) self.shortIndentLess = QShortcut(short("Indent-less"), self.ide) self.shortHideMisc = QShortcut(short("Hide-misc"), self.ide) self.shortHideEditor = QShortcut(short("Hide-editor"), self.ide) self.shortHideExplorer = QShortcut(short("Hide-explorer"), self.ide) self.shortRunFile = QShortcut(short("Run-file"), self.ide) self.shortRunProject = QShortcut(short("Run-project"), self.ide) self.shortSwitchFocus = QShortcut(short("Switch-Focus"), self.ide) self.shortStopExecution = QShortcut(short("Stop-execution"), self.ide) self.shortHideAll = QShortcut(short("Hide-all"), self.ide) self.shortFullscreen = QShortcut(short("Full-screen"), self.ide) self.shortFind = QShortcut(short("Find"), self.ide) self.shortFindNext = QShortcut(short("Find-next"), self.ide) self.shortFindPrevious = QShortcut(short("Find-previous"), self.ide) self.shortFindReplace = QShortcut(short("Find-replace"), self.ide) self.shortFindWithWord = QShortcut(short("Find-with-word"), self.ide) self.shortHelp = QShortcut(short("Help"), self.ide) self.shortSplitHorizontal = QShortcut(short("Split-horizontal"), self.ide) self.shortSplitVertical = QShortcut(short("Split-vertical"), self.ide) self.shortFollowMode = QShortcut(short("Follow-mode"), self.ide) self.shortReloadFile = QShortcut(short("Reload-file"), self.ide) self.shortFindInFiles = QShortcut(short("Find-in-files"), self.ide) self.shortImport = QShortcut(short("Import"), self.ide) self.shortGoToDefinition = QShortcut(short("Go-to-definition"), self.ide) self.shortCompleteDeclarations = QShortcut( short("Complete-Declarations"), self.ide) self.shortCodeLocator = QShortcut(short("Code-locator"), self.ide) self.shortFileOpener = QShortcut(short("File-Opener"), self.ide) self.shortNavigateBack = QShortcut(short("Navigate-back"), self.ide) self.shortNavigateForward = QShortcut(short("Navigate-forward"), self.ide) self.shortOpenLastTabOpened = QShortcut(short("Open-recent-closed"), self.ide) self.shortShowCodeNav = QShortcut(short("Show-Code-Nav"), self.ide) self.shortShowPasteHistory = QShortcut(short("Show-Paste-History"), self.ide) self.shortPasteHistory = QShortcut(short("History-Paste"), self.ide) self.shortCopyHistory = QShortcut(short("History-Copy"), self.ide) self.shortHighlightWord = QShortcut(short("Highlight-Word"), self.ide) self.shortChangeSplitFocus = QShortcut(short("change-split-focus"), self.ide) self.shortMoveTabSplit = QShortcut(short("move-tab-to-next-split"), self.ide) self.shortChangeTabVisibility = QShortcut( short("change-tab-visibility"), self.ide) #Connect Shortcuts Signals self.shortNavigateBack.activated.connect(lambda: self.__navigate_with_keyboard(False)) self.shortNavigateForward.activated.connect(lambda: self.__navigate_with_keyboard(True)) self.shortCodeLocator.activated.connect(self.ide.status.show_locator) self.shortFileOpener.activated.connect(self.ide.status.show_file_opener) self.shortGoToDefinition.activated.connect(self.editor_go_to_definition) self.shortCompleteDeclarations.activated.connect(self.editor_complete_declaration) self.shortRedo.activated.connect(self.editor_redo) self.shortHorizontalLine.activated.connect(self.editor_insert_horizontal_line) self.shortTitleComment.activated.connect(self.editor_insert_title_comment) self.shortFollowMode.activated.connect(self.ide.mainContainer.show_follow_mode) self.shortReloadFile.activated.connect(self.ide.mainContainer.reload_file) self.shortSplitHorizontal.activated.connect(lambda: self.ide.mainContainer.split_tab(True)) self.shortSplitVertical.activated.connect(lambda: self.ide.mainContainer.split_tab(False)) self.shortNew.activated.connect(self.ide.mainContainer.add_editor) self.shortNewProject.activated.connect(self.ide.explorer.create_new_project) self.shortHideMisc.activated.connect(self.view_misc_visibility) self.shortHideEditor.activated.connect(self.view_main_visibility) self.shortHideExplorer.activated.connect(self.view_explorer_visibility) self.shortHideAll.activated.connect(self.hide_all) self.shortFullscreen.activated.connect(self.fullscreen_mode) self.shortOpen.activated.connect(self.ide.mainContainer.open_file) self.shortOpenProject.activated.connect(self.open_project) self.shortCloseTab.activated.connect(self.ide.mainContainer.close_tab) self.shortSave.activated.connect(self.ide.mainContainer.save_file) self.shortSaveProject.activated.connect(self.save_project) self.shortPrint.activated.connect(self.print_file) self.shortFind.activated.connect(self.ide.status.show) self.shortFindPrevious.activated.connect(self.ide.status._searchWidget.find_previous) self.shortFindNext.activated.connect(self.ide.status._searchWidget.find_next) self.shortFindWithWord.activated.connect(self.ide.status.show_with_word) self.shortFindReplace.activated.connect(self.ide.status.show_replace) self.shortRunFile.activated.connect(self.execute_file) self.shortRunProject.activated.connect(self.execute_project) self.shortSwitchFocus.activated.connect(self.switch_focus) self.shortStopExecution.activated.connect(self.kill_execution) self.shortIndentLess.activated.connect(self.editor_indent_less) self.shortComment.activated.connect(self.editor_comment) self.shortUncomment.activated.connect(self.editor_uncomment) self.shortHelp.activated.connect(self.ide.mainContainer.show_python_doc) self.shortImport.activated.connect(self.import_from_everywhere) self.shortFindInFiles.activated.connect(self.ide.misc.show_find_in_files_widget) self.shortMoveUp.activated.connect(self.editor_move_up) self.shortMoveDown.activated.connect(self.editor_move_down) self.shortRemove.activated.connect(self.editor_remove_line) self.shortDuplicate.activated.connect(self.editor_duplicate) self.shortOpenLastTabOpened.activated.connect(self.reopen_last_tab) self.shortChangeTab.activated.connect(self.ide.mainContainer.change_tab) self.shortChangeTabReverse.activated.connect(self.ide.mainContainer.change_tab_reverse) self.shortMoveTabToRight.activated.connect(self.move_tab) self.shortMoveTabToLeft.activated.connect(lambda: self.move_tab(next=False)) self.shortShowCodeNav.activated.connect(self.ide.mainContainer.show_navigation_buttons) self.shortAddBookmark.activated.connect(self._add_bookmark_breakpoint) self.shortShowPasteHistory.activated.connect(self.ide.central.lateralPanel.combo.showPopup) self.shortCopyHistory.activated.connect(self._copy_history) self.shortPasteHistory.activated.connect(self._paste_history) self.shortHighlightWord.activated.connect(self.editor_highlight_word) self.shortChangeSplitFocus.activated.connect(self.ide.mainContainer.change_split_focus) self.shortMoveTabSplit.activated.connect(self.move_tab_to_next_split) self.shortChangeTabVisibility.activated.connect(self.ide.mainContainer.change_tabs_visibility) key = Qt.Key_1 for i in range(10): if sys.platform == "darwin": short = TabShortcuts( QKeySequence(Qt.CTRL + Qt.ALT + key), self.ide, i) else: short = TabShortcuts(QKeySequence(Qt.ALT + key), self.ide, i) key += 1 short.activated.connect(self._change_tab_index) short = TabShortcuts(QKeySequence(Qt.ALT + Qt.Key_0), self.ide, 10) short.activated.connect(self._change_tab_index) #Connect SIGNALs from other objects self.ide.mainContainer._tabMain.runFile.connect(self.execute_file) self.ide.mainContainer._tabSecondary.runFile.connect(self.execute_file) self.ide.mainContainer._tabMain.addToProject[str].connect(self._add_file_to_project) self.ide.mainContainer._tabSecondary.addToProject[str].connect(self._add_file_to_project) self.ide.mainContainer.openProject[str].connect(self.open_project) # Not Configurable Shortcuts self._shortEscStatus = QShortcut(QKeySequence(Qt.Key_Escape), self.ide.status) self._shortEscMisc = QShortcut(QKeySequence(Qt.Key_Escape), self.ide.misc) self._shortEscStatus.activated.connect(self.ide.status.hide_status) self._shortEscMisc.activated.connect(self.ide.misc.hide)
def __init__(self, controller: 'Controller') -> None: super().__init__() self._controller = controller self.setCacheMode(QGraphicsView.CacheBackground) self.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) # self.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn) self._show_filtered = False self._location2item: Dict[Location, List[FileItem]] = defaultdict(list) self.setAcceptDrops(True) self._scene = FileGraphicsScene() self._scene.sig_files_drop.connect(self._controller.on_files_drop) self.setScene(self._scene) self._scene.selectionChanged.connect(self.on_selection_changed) self._style = FileViewStyle() self._modes: List[Mode] = [ IconMode(self), ListMode(self), DetailMode(self) ] self._mode = self._modes[FileItemStyle.ICON.value] self._layout: Optional[RootLayout] = None self._items: List[FileItem] = [] self._file_collection: Optional[FileCollection] = None self._needs_layout = True self.apply_zoom() self._cursor_item: Optional[FileItem] = None self._crop_thumbnails = False self.setBackgroundBrush(QBrush(Qt.white, Qt.SolidPattern)) self._resize_timer: Optional[int] = None self.setDragMode(QGraphicsView.RubberBandDrag) self.setRenderHints(QPainter.SmoothPixmapTransform | QPainter.TextAntialiasing | QPainter.Antialiasing) shortcut = QShortcut(QKeySequence(Qt.CTRL + Qt.Key_G), self) shortcut.setContext(Qt.WidgetShortcut) shortcut.activated.connect(self._on_reset) shortcut = QShortcut(QKeySequence(Qt.Key_Slash), self) shortcut.setContext(Qt.WidgetShortcut) shortcut.activated.connect(lambda: self._controller.show_location_toolbar(False)) self._leap_widget = LeapWidget(self) self._leap_widget.sig_leap.connect(self.leap_to) self._scroll_timer = None self._is_scrolling = False self.verticalScrollBar().sliderReleased.connect(self._on_vertical_scrollbar_slider_released) self.verticalScrollBar().valueChanged.connect(self._on_vertical_scrollbar_slider_value_changed)
def __init__(self, parent=None): super(MainWindow, self).__init__(parent) self.fnames = [] # list of file names to be converted self.office_listener_started = False self.parse_cla() addQPB = QPushButton(self.tr('Add')) delQPB = QPushButton(self.tr('Delete')) clearQPB = QPushButton(self.tr('Clear')) vlayout1 = utils.add_to_layout('v', addQPB, delQPB, clearQPB, None) self.filesList = utils.FilesList() self.filesList.setSelectionMode(QAbstractItemView.ExtendedSelection) hlayout1 = utils.add_to_layout('h', self.filesList, vlayout1) outputQL = QLabel(self.tr('Output folder:')) self.toQLE = QLineEdit() self.toQLE.setReadOnly(True) self.toQTB = QToolButton() self.toQTB.setText('...') hlayout2 = utils.add_to_layout('h', outputQL, self.toQLE, self.toQTB) self.audiovideo_tab = AudioVideoTab(self) self.image_tab = ImageTab(self) self.document_tab = DocumentTab(self) self.tabs = [self.audiovideo_tab, self.image_tab, self.document_tab] tab_names = [self.tr('Audio/Video'), self.tr('Images'), self.tr('Documents')] self.tabWidget = QTabWidget() for num, tab in enumerate(tab_names): self.tabWidget.addTab(self.tabs[num], tab) self.tabWidget.setCurrentIndex(0) self.origQCB = QCheckBox( self.tr('Save each file in the same\nfolder as input file')) self.deleteQCB = QCheckBox(self.tr('Delete original')) convertQPB = QPushButton(self.tr('&Convert')) hlayout3 = utils.add_to_layout('h', self.origQCB, self.deleteQCB, None) hlayout4 = utils.add_to_layout('h', None, convertQPB) final_layout = utils.add_to_layout( 'v', hlayout1, self.tabWidget, hlayout2, hlayout3, hlayout4) self.dependenciesQL = QLabel() self.statusBar().addPermanentWidget(self.dependenciesQL, stretch=1) widget = QWidget() widget.setLayout(final_layout) self.setCentralWidget(widget) openAction = utils.create_action( self, self.tr('Open'), QKeySequence.Open, None, self.tr('Open a file'), self.filesList_add ) convertAction = utils.create_action( self, self.tr('Convert'), 'Ctrl+C', None, self.tr('Convert files'), self.start_conversion ) quitAction = utils.create_action( self, self.tr('Quit'), 'Ctrl+Q', None, self.tr('Quit'), self.close ) edit_presetsAction = utils.create_action( self, self.tr('Edit Presets'), 'Ctrl+P', None, self.tr('Edit Presets'), self.open_dialog_presets ) importAction = utils.create_action( self, self.tr('Import'), None, None, self.tr('Import presets'), self.import_presets ) exportAction = utils.create_action( self, self.tr('Export'), None, None, self.tr('Export presets'), self.export_presets ) resetAction = utils.create_action( self, self.tr('Reset'), None, None, self.tr('Reset presets'), self.reset_presets ) syncAction = utils.create_action( self, self.tr('Synchronize'), None, None, self.tr('Synchronize presets'), self.sync_presets ) removeoldAction = utils.create_action( self, self.tr('Remove old'), None, None, self.tr('Remove old presets'), self.removeold_presets ) clearallAction = utils.create_action( self, self.tr('Clear All'), None, None, self.tr('Clear form'), self.clear_all ) preferencesAction = utils.create_action( self, self.tr('Preferences'), 'Alt+Ctrl+P', None, self.tr('Preferences'), self.open_dialog_preferences ) trackerAction = utils.create_action( self, 'Issue tracker', None, None, None, lambda: webbrowser.open( "https://github.com/Ilias95/FF-Multi-Converter/issues") ) wikiAction = utils.create_action( self, 'Wiki', None, None, None, lambda: webbrowser.open( "https://github.com/Ilias95/FF-Multi-Converter/wiki") ) ffmpegdocAction = utils.create_action( self, 'FFmpeg ' + self.tr('documentation'), None, None, None, lambda: webbrowser.open( "https://www.ffmpeg.org/documentation.html") ) imagemagickdocAction = utils.create_action( self, 'ImageMagick ' + self.tr('documentation'), None, None, None, lambda: webbrowser.open( "http://www.imagemagick.org/script/convert.php") ) aboutAction = utils.create_action( self, self.tr('About'), 'Ctrl+?', None, self.tr('About'), self.open_dialog_about ) fileMenu = self.menuBar().addMenu(self.tr('File')) editMenu = self.menuBar().addMenu(self.tr('Edit')) presetsMenu = self.menuBar().addMenu(self.tr('Presets')) helpMenu = self.menuBar().addMenu(self.tr('Help')) utils.add_actions( fileMenu, [openAction, convertAction, None, quitAction]) utils.add_actions( presetsMenu, [edit_presetsAction, importAction, exportAction, resetAction, None, syncAction, removeoldAction] ) utils.add_actions(editMenu, [clearallAction, None, preferencesAction]) utils.add_actions( helpMenu, [trackerAction, wikiAction, None, ffmpegdocAction, imagemagickdocAction, None, aboutAction] ) self.filesList.dropped.connect(self.filesList_add_dragged) addQPB.clicked.connect(self.filesList_add) delQPB.clicked.connect(self.filesList_delete) clearQPB.clicked.connect(self.filesList_clear) self.tabWidget.currentChanged.connect( lambda: self.tabs[0].moreQPB.setChecked(False)) self.origQCB.toggled.connect( lambda: self.toQLE.setEnabled(not self.origQCB.isChecked())) self.toQTB.clicked.connect(self.get_output_folder) convertQPB.clicked.connect(convertAction.triggered) del_shortcut = QShortcut(self) del_shortcut.setKey(Qt.Key_Delete) del_shortcut.activated.connect(self.filesList_delete) self.setWindowTitle('FF Multi Converter') self.load_settings() self.check_for_dependencies() self.audiovideo_tab.set_default_command() self.image_tab.set_default_command() self.toQLE.setText(self.default_output) self.filesList_update()
def install_shortcuts(obj, actions, ide): short = resources.get_shortcut for action in actions: short_key = action.get("shortcut", None) action_data = action.get("action", None) connect = action.get("connect", None) shortcut = None item_ui = None func = None if connect is not None: func = getattr(obj, connect, None) if short_key and not action_data: if isinstance(short_key, QKeySequence): shortcut = QShortcut(short_key, ide) else: if short(short_key) is None: logger.warning("Not shorcut for %s" % short_key) continue shortcut = QShortcut(short(short_key), ide) shortcut.setContext(Qt.ApplicationShortcut) if isinstance(func, collections.Callable): shortcut.activated.connect(func) if action_data: is_menu = action_data.get('is_menu', False) if is_menu: item_ui = QMenu(action_data['text'], ide) else: item_ui = QAction(action_data['text'], ide) object_name = "%s.%s" % (obj.__class__.__name__, connect) item_ui.setObjectName(object_name) # FIXME: Configurable item_ui.setIconVisibleInMenu(False) image_name = action_data.get('image', None) section = action_data.get('section', None) weight = action_data.get('weight', None) keysequence = action_data.get('keysequence', None) if image_name: if isinstance(image_name, int): icon = ide.style().standardIcon(image_name) item_ui.setIcon(icon) elif isinstance(image_name, str): if image_name.startswith("/home"): icon = QIcon(image_name) else: icon = QIcon(":img/" + image_name) item_ui.setIcon(icon) if short_key and not is_menu: if short(short_key) is None: logger.warning("Not shortcut for %s" % short_key) continue item_ui.setShortcut(short(short_key)) # Add tooltip with append shortcut item_ui.setToolTip( tooltip_with_shortcut(item_ui.text(), short(short_key))) item_ui.setShortcutContext(Qt.ApplicationShortcut) elif keysequence and not is_menu: item_ui.setShortcut(short(keysequence)) item_ui.setShortcutContext(Qt.ApplicationShortcut) if isinstance(func, collections.Callable) and not is_menu: item_ui.triggered.connect(lambda _, func=func: func()) if section and section[0] is not None and weight: ide.register_menuitem(item_ui, section, weight) if image_name and not is_menu: ide.register_toolbar(item_ui, section, weight) if short_key and shortcut: ide.register_shortcut(short_key, shortcut, item_ui)
class EditTerrainDialog(QDialog): def __init__(self, mapDocument, tileset, parent = None): super().__init__(parent) self.mUi = Ui_EditTerrainDialog() self.mMapDocument = mapDocument self.mInitialUndoStackIndex = self.mMapDocument.undoStack().index() self.mTileset = tileset self.mUi.setupUi(self) self.setWindowFlags(self.windowFlags() & ~Qt.WindowContextHelpButtonHint) Utils.setThemeIcon(self.mUi.redo, "edit-redo") Utils.setThemeIcon(self.mUi.undo, "edit-undo") zoomable = Zoomable(self) zoomable.connectToComboBox(self.mUi.zoomComboBox) tilesetModel = TilesetModel(self.mTileset, self.mUi.tilesetView) mapDocument.tileTerrainChanged.connect(tilesetModel.tilesChanged) self.mUi.tilesetView.setEditTerrain(True) self.mUi.tilesetView.setMapDocument(mapDocument) self.mUi.tilesetView.setZoomable(zoomable) self.mUi.tilesetView.setModel(tilesetModel) self.mTerrainModel = mapDocument.terrainModel() rootIndex = self.mTerrainModel.index(tileset) self.mUi.terrainList.setMapDocument(mapDocument) self.mUi.terrainList.setModel(self.mTerrainModel) self.mUi.terrainList.setRootIndex(rootIndex) terrainListHeader = self.mUi.terrainList.header() terrainListHeader.setSectionResizeMode(0, QHeaderView.ResizeToContents) selectionModel = self.mUi.terrainList.selectionModel() selectionModel.currentRowChanged.connect(self.selectedTerrainChanged) if (self.mTerrainModel.rowCount(rootIndex) > 0): selectionModel.setCurrentIndex(self.mTerrainModel.index(0, 0, rootIndex), QItemSelectionModel.SelectCurrent | QItemSelectionModel.Rows) self.mUi.terrainList.setFocus() self.mUi.eraseTerrain.toggled.connect(self.eraseTerrainToggled) self.mUi.addTerrainTypeButton.clicked.connect(self.addTerrainType) self.mUi.removeTerrainTypeButton.clicked.connect(self.removeTerrainType) self.mUi.tilesetView.createNewTerrainSignal.connect(self.addTerrainType) self.mUi.tilesetView.terrainImageSelected.connect(self.setTerrainImage) undoStack = mapDocument.undoStack() undoStack.indexChanged.connect(self.updateUndoButton) undoStack.canRedoChanged.connect(self.mUi.redo.setEnabled) self.mUi.undo.clicked.connect(undoStack.undo) self.mUi.redo.clicked.connect(undoStack.redo) self.mUndoShortcut = QShortcut(QKeySequence.Undo, self) self.mRedoShortcut = QShortcut(QKeySequence.Redo, self) self.mUndoShortcut.activated.connect(undoStack.undo) self.mRedoShortcut.activated.connect(undoStack.redo) eraseShortcut = QShortcut(QKeySequence(self.tr("E")), self) eraseShortcut.activated.connect(self.mUi.eraseTerrain.toggle) self.updateUndoButton() Utils.restoreGeometry(self) def __del__(self): Utils.saveGeometry(self) del self.mUi def selectedTerrainChanged(self, index): terrainId = -1 terrain = self.mTerrainModel.terrainAt(index) if terrain: terrainId = terrain.id() self.mUi.tilesetView.setTerrainId(terrainId) self.mUi.removeTerrainTypeButton.setEnabled(terrainId != -1) def eraseTerrainToggled(self, checked): self.mUi.tilesetView.setEraseTerrain(checked) def addTerrainType(self, tile = None): if tile: x = tile.id() else: x = -1 terrain = Terrain(self.mTileset.terrainCount(), self.mTileset, QString(), x) terrain.setName(self.tr("New Terrain")) self.mMapDocument.undoStack().push(AddTerrain(self.mMapDocument, terrain)) # Select the newly added terrain and edit its name index = self.mTerrainModel.index(terrain) selectionModel = self.mUi.terrainList.selectionModel() selectionModel.setCurrentIndex(index, QItemSelectionModel.ClearAndSelect | QItemSelectionModel.Rows) self.mUi.terrainList.edit(index) def removeTerrainType(self): currentIndex = self.mUi.terrainList.currentIndex() if (not currentIndex.isValid()): return terrain = self.mTerrainModel.terrainAt(currentIndex) removeTerrain = RemoveTerrain(self.mMapDocument, terrain) ## # Clear any references to the terrain that is about to be removed with # an undo command, as a way of preserving them when undoing the removal # of the terrain. ## changes = ChangeTileTerrain.Changes() for tile in terrain.tileset().tiles(): tileTerrain = tile.terrain() for corner in range(4): if (tile.cornerTerrainId(corner) == terrain.id()): tileTerrain = setTerrainCorner(tileTerrain, corner, 0xFF) if (tileTerrain != tile.terrain()): changes.insert(tile, ChangeTileTerrain.Change(tile.terrain(), tileTerrain)) undoStack = self.mMapDocument.undoStack() if (not changes.isEmpty()): undoStack.beginMacro(removeTerrain.text()) undoStack.push(ChangeTileTerrain(self.mMapDocument, changes)) self.mMapDocument.undoStack().push(removeTerrain) if (not changes.isEmpty()): undoStack.endMacro() ## # Removing a terrain usually changes the selected terrain without the # selection changing rows, so we can't rely on the currentRowChanged # signal. ## self.selectedTerrainChanged(self.mUi.terrainList.currentIndex()) def setTerrainImage(self, tile): currentIndex = self.mUi.terrainList.currentIndex() if (not currentIndex.isValid()): return terrain = self.mTerrainModel.terrainAt(currentIndex) self.mMapDocument.undoStack().push(SetTerrainImage(self.mMapDocument, terrain.tileset(), terrain.id(), tile.id())) def updateUndoButton(self): undoStack = self.mMapDocument.undoStack() canUndo = undoStack.index() > self.mInitialUndoStackIndex canRedo = undoStack.canRedo() self.mUi.undo.setEnabled(canUndo) self.mUi.redo.setEnabled(canRedo) self.mUndoShortcut.setEnabled(canUndo) self.mRedoShortcut.setEnabled(canRedo)
def __init__(self): QMainWindow.__init__(self) Ui_MainWindow.setupUi(self, self) self.playlistDrop.dragEnterEvent = self.playlistDragEnterEvent self.playlistDrop.dropEvent = self.playlistDropEvent self.playlistModel = PlaylistModel() self.playlistTable.setModel(self.playlistModel) self.playlistTable.customContextMenuRequested.connect(self.playlistContextMenu) self.playlistTable.doubleClicked.connect(self.onPlaylistDoubleClick) self.playback = PlaybackWidget(self) self.playbackLayout.addWidget(self.playback) self.playback.playButton.clicked.connect(self.onPlaySelected) self.playback.nextButton.clicked.connect(self.onNextClicked) self.playback.prevButton.clicked.connect(self.onPrevClicked) self.libraryDock.setTitleBarWidget(QWidget()) self.playlistsDock.setTitleBarWidget(QWidget()) self.toggleLibraryButton.clicked.connect(self.onToggleLibrary) self.togglePlaylistsButton.clicked.connect(self.onTogglePlaylists) self.library = LibraryWidget(self) self.libraryDock.setWidget(self.library) self.libraryDock.hide() self.library.itemsActivated.connect(self.onLibraryItemActivated) self.playlists = PlaylistsWidget(self) self.playlistsDock.setWidget(self.playlists) self.playlistsDock.hide() self.playlists.loadPlaylist.connect(self.onPlaylistLoad) self.dockState = 0 self.settings = QSettings('txplaya', 'txplaya') if u'geometry/main' in self.settings.allKeys(): self.setGeometry(self.settings.value(u'geometry/main')) for col in range(self.playlistModel.columnCount()): width = self.settings.value(u'geometry/playlist/col/%d' % col) self.playlistTable.setColumnWidth(col, int(width)) dockState = int(self.settings.value(u'geometry/dock/state')) self.dockShow(dockState) self.systemTray = QSystemTrayIcon(self.windowIcon()) self.systemTray.setToolTip('Playa') self.systemTray.show() self.systemTray.activated.connect(self.systemTrayToggle) systemTrayMenu = QMenu() systemTrayMenu.addAction(self.restore) systemTrayMenu.addAction(self.quit) self.systemTray.setContextMenu(systemTrayMenu) self.restore.triggered.connect(self.restoreWindow) self.quit.triggered.connect(self.quitEvent) self.quitButton.clicked.connect(self.quitEvent) self.quitFlag = False # keyboard shortcuts focusLibraryShortcut = QShortcut(QKeySequence('Ctrl+F'), self) focusLibraryShortcut.activated.connect(self.onFocusLibrary) deleteTrackShortcut = QShortcut(QKeySequence('Del'), self.playlistTable) deleteTrackShortcut.setContext(Qt.WidgetShortcut) deleteTrackShortcut.activated.connect(self.onDeleteTrack) togglePlaybackShortcut = QShortcut(QKeySequence('Space'), self) togglePlaybackShortcut.activated.connect(self.onTogglePlayback) startShortcut = QShortcut(QKeySequence(Qt.Key_Return), self.playlistTable) startShortcut.setContext(Qt.WidgetShortcut) startShortcut.activated.connect(self.onPlaySelected) undoShortcut = QShortcut(QKeySequence('Ctrl+Z'), self) undoShortcut.activated.connect(self.onPlaylistUndo) redoShortcut = QShortcut(QKeySequence('Ctrl+Shift+Z'), self) redoShortcut.activated.connect(self.onPlaylistRedo) saveShortcut = QShortcut(QKeySequence('Ctrl+S'), self) saveShortcut.activated.connect(self.onPlaylistSave) self.infoStreamStart() QTimer.singleShot(200, self.fetchLibrary)
def initUI(self): self.setWindowTitle(self.title) self.setWindowIcon(self.icon) self.setGeometry(self.left, self.top, self.width, self.height) self.msgSc = QShortcut(QKeySequence("Ctrl+M"), self) self.msgSc.activated.connect(self.test_message) rootLayout = QVBoxLayout() # rootLayout.setAlignment(Qt.AlignTop) self.imageDirLine = QLineEdit('test_images', self) self.imageDirLine.setPlaceholderText('Images folder') self.maskDirLine = QLineEdit('test_masks', self) self.maskDirLine.setPlaceholderText('Raw masks folder (optional)') self.outDirLine = QLineEdit('test_output', self) self.outDirLine.setPlaceholderText('Output folder') self.targetSizeLine = QLineEdit('768', self) self.targetSizeLine.setValidator(QIntValidator(64, 1024, self)) self.targetSizeLine.setPlaceholderText('Target size (default: 512px)') self.rootBtn = QPushButton("Apply") self.resultLabel = QLabel("Num Files: 0") self.resultLabel.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Fixed) self.resultLabel.setAlignment(Qt.AlignTop) rootLayout.addWidget(self.imageDirLine) rootLayout.addWidget(self.maskDirLine) rootLayout.addWidget(self.outDirLine) rootLayout.addWidget(self.targetSizeLine) rootLayout.addWidget(self.rootBtn) rootLayout.addWidget(self.resultLabel, 0) self.rootBtn.clicked.connect(self.apply_root_dir) control_layout = self.create_control_layout() ## Create widget self.label = QMainLabel(self) self.label.load_pixmap('media/512.png') self.sh = QShortcut(QKeySequence("Ctrl+Z"), self) self.sh.activated.connect(self.label.restore_original) layout = QHBoxLayout() layout.addWidget(self.label) # self.resize(pixmap.width(),pixmap.height()) rotate_slider, rotate_label = self.add_slider() rotate_layout = QVBoxLayout() rotate_layout.addWidget(rotate_label) rotate_layout.addWidget(rotate_slider) self.rotate_label = rotate_label self.rotate_slider = rotate_slider tools_layout = self.build_toolbox() layout = QHBoxLayout() btn_layout = QVBoxLayout() btn_layout.addLayout(rootLayout) btn_layout.addLayout(control_layout) btn_layout.addLayout(tools_layout) btn_layout.addLayout(rotate_layout) btn_layout.addWidget(QPushButton("Left-Most"), 1) btn_layout.addWidget(QPushButton("Center"), 1) btn_layout.addWidget(QPushButton("Right-Most"), 2) layout.addLayout(btn_layout) layout.addLayout(rootLayout) layout.addWidget(self.label) central_widget = QWidget(self) central_widget.setLayout(layout) self.setCentralWidget(central_widget) self.show()
class comics_project_page_viewer(QDialog): pageIndex = 0 spread = True def __init__(self): super().__init__() self.setModal(False) self.setWindowTitle('Untitled') self.setWindowFlags(Qt.WindowTitleHint | Qt.WindowMinimizeButtonHint | Qt.WindowMaximizeButtonHint | Qt.WindowCloseButtonHint) self.resize(1024, 768) self.setLayout(QVBoxLayout()) self.left_viewer = page_viewer() self.left_viewer.align_right() self.left_viewer.clicked.connect(self.prev_page) self.right_viewer = page_viewer() self.right_viewer.align_left() self.right_viewer.clicked.connect(self.next_page) self.single_viewer = page_viewer() self.single_viewer.align_center() self.single_viewer.clicked.connect(self.next_page) self.single_viewer.hide() self.page_layout = QHBoxLayout() self.layout().addLayout(self.page_layout) self.page_layout.addWidget(self.left_viewer) self.page_layout.addWidget(self.right_viewer) self.page_layout.addWidget(self.single_viewer) # Keyboard shortcuts self.home_shortcut = QShortcut('Home', self) self.home_shortcut.activated.connect(self.first_page) self.left_shortcut = QShortcut('Left', self) self.left_shortcut.activated.connect(self.prev_page) self.right_shortcut = QShortcut('Right', self) self.right_shortcut.activated.connect(self.next_page) self.space_shortcut = QShortcut('Space', self) self.space_shortcut.activated.connect(self.next_page) self.end_shortcut = QShortcut('End', self) self.end_shortcut.activated.connect(self.last_page) self.first_btn = QPushButton('First') self.first_btn.clicked.connect(self.first_page) self.prev_btn = QPushButton('Previous') self.prev_btn.clicked.connect(self.prev_page) self.spread_btn = QPushButton('Single Page') self.spread_btn.clicked.connect(self.toggle_spread) self.next_btn = QPushButton('Next') self.next_btn.clicked.connect(self.next_page) self.last_btn = QPushButton('Last') self.last_btn.clicked.connect(self.last_page) self.buttons_layout = QHBoxLayout() self.layout().addLayout(self.buttons_layout) self.buttons_layout.addWidget(self.first_btn) self.buttons_layout.addWidget(self.prev_btn) self.buttons_layout.addWidget(self.spread_btn) self.buttons_layout.addWidget(self.next_btn) self.buttons_layout.addWidget(self.last_btn) def load_comic(self, path_to_config): self.path_to_config = path_to_config configFile = open(self.path_to_config, "r", newline="", encoding="utf-16") self.setupDictionary = json.load(configFile) self.projecturl = os.path.dirname(str(self.path_to_config)) if 'readingDirection' in self.setupDictionary: if self.setupDictionary['readingDirection'] == "leftToRight": self.setLayoutDirection(Qt.LeftToRight) self.left_shortcut.disconnect() self.right_shortcut.disconnect() self.left_shortcut.activated.connect(self.prev_page) self.right_shortcut.activated.connect(self.next_page) else: self.left_shortcut.disconnect() self.right_shortcut.disconnect() self.setLayoutDirection(Qt.RightToLeft) self.left_shortcut.activated.connect(self.next_page) self.right_shortcut.activated.connect(self.prev_page) else: self.left_shortcut.disconnect() self.right_shortcut.disconnect() self.setLayoutDirection(Qt.LeftToRight) self.left_shortcut.activated.connect(self.prev_page) self.right_shortcut.activated.connect(self.next_page) configFile.close() def go_to_page_index(self, index): if index >= 0 and index < len(self.setupDictionary['pages']): self.pageIndex = index else: self.pageIndex = 0 self.flip_page() def toggle_spread(self): if self.spread: self.spread = False self.spread_btn.setText('Double Spread') self.update_single_page(self.pageIndex) self.left_viewer.hide() self.right_viewer.hide() self.single_viewer.show() self.flip_page() else: self.spread = True self.spread_btn.setText('Single Page') self.left_viewer.show() self.right_viewer.show() self.single_viewer.hide() self.flip_page() def update_single_page(self, index): image = self.get_mergedimage(index) self.single_viewer.set_image(image) def update_left_page(self, index): image = self.get_mergedimage(index) self.left_viewer.set_image(image) def update_right_page(self, index): image = self.get_mergedimage(index) self.right_viewer.set_image(image) def first_page(self): self.pageIndex = 0 self.flip_page() def prev_page(self): if self.pageIndex <= 0: self.pageIndex = len(self.setupDictionary['pages']) - 1 else: if self.spread: self.pageIndex -= 2 else: self.pageIndex -= 1 self.flip_page() def next_page(self): if self.pageIndex >= len(self.setupDictionary['pages']) - 1: self.pageIndex = 0 else: if self.spread: self.pageIndex += 2 else: self.pageIndex += 1 self.flip_page() def last_page(self): self.pageIndex = len(self.setupDictionary['pages']) - 1 self.flip_page() def flip_page(self): if self.spread: if self.pageIndex % 2 == 0: # Even/Left left_page_number = self.pageIndex - 1 right_page_number = self.pageIndex else: # Odd/Right left_page_number = self.pageIndex right_page_number = self.pageIndex + 1 self.update_left_page(left_page_number) self.update_right_page(right_page_number) if left_page_number < 0: page_numbers = str(right_page_number + 1) elif right_page_number >= len(self.setupDictionary['pages']): page_numbers = str(left_page_number + 1) else: page_numbers = '{left} / {right}'.format( left=str(left_page_number + 1), right=str(right_page_number + 1)) self.setWindowTitle('{name} - {page_numbers}'.format( name=self.setupDictionary['projectName'], page_numbers=page_numbers)) else: if self.pageIndex >= len(self.setupDictionary['pages']): self.pageIndex = len(self.setupDictionary['pages']) - 1 if self.pageIndex < 0: self.pageIndex = 0 self.update_single_page(self.pageIndex) self.setWindowTitle('{name} - {page_numbers}'.format( name=self.setupDictionary['projectName'], page_numbers=str(self.pageIndex + 1))) def get_mergedimage(self, index): if index < len(self.setupDictionary['pages']) and index > -1: image_url = os.path.join(self.projecturl, self.setupDictionary['pages'][index]) if os.path.exists(image_url): page = zipfile.ZipFile(image_url, "r") image = QImage.fromData(page.read("mergedimage.png")) page.close() return image image = QImage(QSize(10, 10), QImage.Format_ARGB32) image.fill(Qt.GlobalColor(19)) return image
def __init__(self, parent=None, choose=False): super(ShowPresets, self).__init__(parent) self.original_presets_file = utils.find_presets_file( config.presets_file_name, config.presets_lookup_dirs, config.presets_lookup_virtenv ) self.current_presets_file = config.presets_file self.presQLW = QListWidget() labelQL = QLabel(self.tr('Preset label')) self.labelQLE = QLineEdit() self.labelQLE.setReadOnly(True) commandQL = QLabel(self.tr('Preset command line parameters')) self.commandQLE = QLineEdit() self.commandQLE.setReadOnly(True) extQL = QLabel(self.tr('Output file extension')) self.extQLE = QLineEdit() self.extQLE.setReadOnly(True) addQPB = QPushButton(self.tr('Add')) self.deleteQPB = QPushButton(self.tr('Delete')) self.delete_allQPB = QPushButton(self.tr('Delete all')) self.editQPB = QPushButton(self.tr('Edit')) searchQL = QLabel(self.tr('Search')) self.searchQLE = QLineEdit() okQPB = QPushButton(self.tr('OK')) okQPB.setDefault(True) spc1 = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum) spc2 = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum) spc3 = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum) grid = utils.add_to_grid( [self.delete_allQPB, addQPB, spc1], [self.deleteQPB, self.editQPB, spc2] ) hlayout = utils.add_to_layout( 'h', searchQL, self.searchQLE, None, okQPB) final_layout = utils.add_to_layout( 'v', self.presQLW, labelQL, self.labelQLE, commandQL, self.commandQLE, extQL, self.extQLE, grid, spc3, hlayout ) self.setLayout(final_layout) okQPB.clicked.connect(self.accept) self.presQLW.currentRowChanged.connect(self.show_preset) addQPB.clicked.connect(self.add_preset) self.deleteQPB.clicked.connect(self.delete_preset) self.delete_allQPB.clicked.connect(self.delete_all_presets) self.editQPB.clicked.connect(self.edit_preset) self.searchQLE.textEdited.connect(self.search) if choose: self.presQLW.doubleClicked.connect(okQPB.click) del_shortcut = QShortcut(self) del_shortcut.setKey(Qt.Key_Delete) del_shortcut.activated.connect(self.delete_preset) self.resize(430, 480) self.setWindowTitle(self.tr('Edit Presets')) QTimer.singleShot(0, self.load_xml) QTimer.singleShot(0, self.fill_presQLW)
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() horizontal_splitter = QSplitter(Qt.Horizontal) vertical_splitter = QSplitter(Qt.Vertical) # 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 = QCheckBox(self) limit_verticalLayout.addWidget(self.after_checkBox) # after_frame self.after_frame = QFrame(self) self.after_frame.setFrameShape(QFrame.StyledPanel) self.after_frame.setFrameShadow(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) horizontal_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) # download_table self.download_table = DownloadTableWidget(self) vertical_splitter.addWidget(self.download_table) horizontal_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) horizontal_splitter.setStretchFactor(0, 3) # category_tree width horizontal_splitter.setStretchFactor(1, 10) # ratio of tables's width # video_finder_widget self.video_finder_widget = QWidget(self) video_finder_horizontalLayout = QHBoxLayout(self.video_finder_widget) self.muxing_pushButton = QPushButton(self) self.muxing_pushButton.setIcon(QIcon(icons + 'video_finder')) video_finder_horizontalLayout.addWidget(self.muxing_pushButton) video_finder_horizontalLayout.addSpacing(20) video_audio_verticalLayout = QVBoxLayout() self.video_label = QLabel(self) video_audio_verticalLayout.addWidget(self.video_label) self.audio_label = QLabel(self) video_audio_verticalLayout.addWidget(self.audio_label) video_finder_horizontalLayout.addLayout(video_audio_verticalLayout) status_muxing_verticalLayout = QVBoxLayout() self.video_finder_status_label = QLabel(self) status_muxing_verticalLayout.addWidget(self.video_finder_status_label) self.muxing_status_label = QLabel(self) status_muxing_verticalLayout.addWidget(self.muxing_status_label) video_finder_horizontalLayout.addLayout(status_muxing_verticalLayout) vertical_splitter.addWidget(self.video_finder_widget) download_table_content_widget_verticalLayout.addWidget(vertical_splitter) download_table_horizontalLayout.addWidget(horizontal_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(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(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.persepolis_setting.beginGroup('settings/shortcuts') # videoFinderAddLinkAction 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) self.videoFinderAddLinkAction_shortcut = QShortcut(self.persepolis_setting.value('video_finder_shortcut'), self, self.showVideoFinderAddLinkWindow) videoFinderMenu.addAction(self.videoFinderAddLinkAction) # stopAllAction 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) # sort_file_name_Action self.sort_file_name_Action = QAction( QCoreApplication.translate("mainwindow_ui_tr", 'File name'), self, triggered=self.sortByName) sortMenu.addAction(self.sort_file_name_Action) # sort_file_size_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) # sort_first_try_date_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) # sort_last_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) # sort_download_status_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) # trayAction 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) # showMenuBarAction 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) # showSidePanelAction 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) # minimizeAction 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) self.minimizeAction_shortcut = QShortcut(self.persepolis_setting.value('hide_window_shortcut'), self, self.minMaxTray) viewMenu.addAction(self.minimizeAction) # addlinkAction 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) self.addlinkAction_shortcut = QShortcut(self.persepolis_setting.value('add_new_download_shortcut'), self, self.addLinkButtonPressed) fileMenu.addAction(self.addlinkAction) # importText 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) self.addtextfileAction_shortcut = QShortcut(self.persepolis_setting.value('import_text_shortcut'), self, self.importText) fileMenu.addAction(self.addtextfileAction) # resumeAction 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) downloadMenu.addAction(self.resumeAction) # pauseAction 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) downloadMenu.addAction(self.pauseAction) # stopAction 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) downloadMenu.addAction(self.stopAction) # propertiesAction self.propertiesAction = QAction(QIcon(icons + 'setting'), QCoreApplication.translate("mainwindow_ui_tr", 'Properties'), self, statusTip=QCoreApplication.translate("mainwindow_ui_tr", "Properties"), triggered=self.propertiesButtonPressed) downloadMenu.addAction(self.propertiesAction) # progressAction self.progressAction = QAction(QIcon(icons + 'window'), QCoreApplication.translate("mainwindow_ui_tr", 'Progress'), self, statusTip=QCoreApplication.translate("mainwindow_ui_tr", "Progress"), triggered=self.progressButtonPressed) downloadMenu.addAction(self.progressAction) # openFileAction 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) # openDownloadFolderAction 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) # openDefaultDownloadFolderAction 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) # exitAction self.exitAction = QAction(QIcon(icons + 'exit'), QCoreApplication.translate("mainwindow_ui_tr", 'Exit'), self, statusTip=QCoreApplication.translate("mainwindow_ui_tr", "Exit"), triggered=self.closeAction) self.exitAction_shortcut = QShortcut(self.persepolis_setting.value('quit_shortcut'), self, self.closeAction) fileMenu.addAction(self.exitAction) # clearAction 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) # removeSelectedAction 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) self.removeSelectedAction_shortcut = QShortcut(self.persepolis_setting.value('remove_shortcut'), self, self.removeSelected) editMenu.addAction(self.removeSelectedAction) self.removeSelectedAction.setEnabled(False) # deleteSelectedAction 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) self.deleteSelectedAction_shortcut = QShortcut(self.persepolis_setting.value('delete_shortcut'), self, self.deleteSelected) editMenu.addAction(self.deleteSelectedAction) self.deleteSelectedAction.setEnabled(False) # moveSelectedDownloadsAction self.moveSelectedDownloadsAction = QAction(QIcon(icons + 'folder'), QCoreApplication.translate("mainwindow_ui_tr", 'move selected download files to another destination'), self, statusTip=QCoreApplication.translate("mainwindow_ui_tr", 'move selected download files to another destination'), triggered=self.moveSelectedDownloads) editMenu.addAction(self.moveSelectedDownloadsAction) self.moveSelectedDownloadsAction.setEnabled(False) # createQueueAction 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) # removeQueueAction 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) # startQueueAction 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) # stopQueueAction 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) # moveUpSelectedAction 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) self.moveUpSelectedAction_shortcut = QShortcut(self.persepolis_setting.value('move_up_selection_shortcut'), self, self.moveUpSelected) queueMenu.addAction(self.moveUpSelectedAction) # moveDownSelectedAction 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) self.moveDownSelectedAction_shortcut = QShortcut(self.persepolis_setting.value('move_down_selection_shortcut'), self, self.moveDownSelected) queueMenu.addAction(self.moveDownSelectedAction) # preferencesAction 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) # aboutAction 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) # issueAction 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) # updateAction 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) # logAction 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) # helpAction 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.persepolis_setting.endGroup() 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")) self.muxing_pushButton.setText(QCoreApplication.translate("mainwindow_ui_tr", "start muxing")) self.video_label.setText(QCoreApplication.translate("mainwindow_ui_tr", "<b>Video file status: </b>")) self.audio_label.setText(QCoreApplication.translate("mainwindow_ui_tr", "<b>Audio file status: </b>")) self.video_finder_status_label.setText(QCoreApplication.translate("mainwindow_ui_tr", "<b>Status: </b>")) self.muxing_status_label.setText(QCoreApplication.translate("mainwindow_ui_tr", "<b>Muxing status: </b>"))
class DockWidget(QDockWidget): """Extended QDockWidget for Enki main window """ closed = pyqtSignal() """ closed() **Signal** emitted, when dock is closed """ shown = pyqtSignal() """ shown() **Signal** emitted, when dock is shown """ def __init__(self, parentObject, windowTitle, windowIcon=QIcon(), shortcut=None): QDockWidget.__init__(self, parentObject) self._showAction = None self.setObjectName(str(self.__class__)) self.setWindowTitle(windowTitle) self.setFeatures(self.features() & (~QDockWidget.DockWidgetFloatable)) if not windowIcon.isNull(): self.setWindowIcon(windowIcon) if shortcut is not None: self.showAction().setShortcut(shortcut) self._titleBar = _TitleBar(self) self.setTitleBarWidget(self._titleBar) if shortcut is not None: toolTip = "Move focus with <b>%s</b>,<br/>close with <b>Esc</b>" % shortcut else: toolTip = "Close with <b>Esc</b>" self._titleBar.setToolTip(toolTip) self._closeShortcut = QShortcut(QKeySequence("Esc"), self) self._closeShortcut.setContext(Qt.WidgetWithChildrenShortcut) self._closeShortcut.activated.connect(self._close) def keyPressEvent(self, event): """Catch Esc. Not using QShortcut, because dock shall be closed, only if child widgets haven't catched Esc event """ if event.key() == Qt.Key_Escape and \ event.modifiers() == Qt.NoModifier: self._hide() else: QDockWidget.keyPressEvent(self, event) def showAction(self): """Action shows the widget and set focus on it. Add this action to the main menu """ if not self._showAction: self._showAction = QAction(self.windowIcon(), self.windowTitle(), self) self._showAction.triggered.connect(self.show) self._showAction.triggered.connect(self._handleFocusProxy) return self._showAction def titleBarWidget(self): """QToolBar on the title. You may add own actions to this tool bar """ # method was added only for documenting return QDockWidget.titleBarWidget(self) def _handleFocusProxy(self): """Set focus to focus proxy. Called after widget has been shown """ if self.focusProxy() is not None: self.setFocus() def _close(self): """Hide and return focus to MainWindow focus proxy """ self.close() if self.parent() is not None and \ self.parent().focusProxy() is not None: self.parent().focusProxy().setFocus() def closeEvent(self, event): """Widget was closed""" self.closed.emit() def showEvent(self, event): """Widget was shown""" self.shown.emit()
l2 = v.addColorTableLayer((raw > 128).astype(numpy.uint8), name="thresh direct=%r" % direct, colortable=colortable, direct=direct) l2.visible = direct return (l1, l2) directLayers = addLayers(v, True) indirectLayers = addLayers(v, False) b = QPushButton("direct mode (Ctrl+d)") b.setCheckable(True) b.setChecked(True) def onDirectModeToggled(direct): for l in directLayers: l.visible = direct for l in indirectLayers: l.visible = not direct b.toggled.connect(onDirectModeToggled) QShortcut(QKeySequence("Ctrl+d"), b, member=b.click, ambiguousMember=b.click) v.rightPaneLayout.addWidget(b) v.show() app.exec_()
def __init__(self, *args, **kwargs): QtWidgets.QMainWindow.__init__(self, *args, **kwargs) self.setupUi(self) self.btn_entrar.clicked.connect(self.entrar) self.shortcut = QShortcut(QKeySequence("Return"), self) self.shortcut.activated.connect(self.entrar)
class SEELIGHTTHREAD(QWidget) : '''open and plot file : SEE(file='nameFile,path=pathFileName,confpath,confMot) Make plot profile ands differents measurements(max,min mean...) Can open .spe .SPE .sif .TIFF files confpath :usefull if more than 2 SEE object used confMot usefull if RSAI motors is read ''' newMesurment=QtCore.pyqtSignal(object) def __init__(self,parent=None,file=None,path=None,**kwds): print('LightThread') super(SEELIGHTTHREAD, self).__init__() self.setStyleSheet(qdarkstyle.load_stylesheet_pyqt5()) # dark style self.parent=parent version=__version__ p = pathlib.Path(__file__) sepa=os.sep self.icon=str(p.parent) + sepa+'icons' +sepa ## kwds definition: if "confpath"in kwds : self.confpath=kwds["confpath"] self.conf=QtCore.QSettings(self.confpath, QtCore.QSettings.IniFormat) else: self.conf=QtCore.QSettings(str(p.parent / 'confVisu.ini'), QtCore.QSettings.IniFormat) if "name" in kwds: self.name=kwds["name"] else: self.name="VISU" if "meas" in kwds: self.meas=kwds["meas"] else: self.meas="on" if "confMot" in kwds: print('motor accepted') if self.meas=="on": self.confMot=kwds["confoMot"] self.winM=MEAS(confMot=self.confMot,conf=self.conf,name=self.name) else : if self.meas=="on": self.winM=MEAS(self,conf=self.conf,name=self.name) if "aff" in kwds: self.aff=kwds["aff"] else: self.aff="left" if "saveTiff" in kwds: self.tiff=kwds["saveTiff"] else: self.tiff=True self.nomFichier='' self.ite=None self.path=path self.setWindowTitle('Visualization'+' v.'+ version) self.bloqKeyboard=bool((self.conf.value(self.name+"/bloqKeyboard")) ) # block cross by keyboard self.bloqq=1 # block the cross by click on mouse self.setup() self.shortcut() self.actionButton() self.activateWindow() self.raise_() self.showNormal() self.setWindowIcon(QIcon(self.icon+'LOA.png')) def twoD_Gaussian(x,y, amplitude, xo, yo, sigma_x, sigma_y, theta, offset): xo = float(xo) yo = float(yo) a = (np.cos(theta)**2)/(2*sigma_x**2) + (np.sin(theta)**2)/(2*sigma_y**2) b = -(np.sin(2*theta))/(4*sigma_x**2) + (np.sin(2*theta))/(4*sigma_y**2) c = (np.sin(theta)**2)/(2*sigma_x**2) + (np.cos(theta)**2)/(2*sigma_y**2) return offset + amplitude*np.exp( - (a*((x-xo)**2) + 2*b*(x-xo)*(y-yo) + c*((y-yo)**2))) if file==None: # to have a gaussian picture when we start self.dimy=960 self.dimx=1240 # Create x and y index self.x = np.arange(0,self.dimx) self.y = np.arange(0,self.dimy) self.y,self.x = np.meshgrid(self.y, self.x) self.data=twoD_Gaussian(self.x, self.y,450, 800, 600, 40, 40, 0, 10)+(50*np.random.rand(self.dimx,self.dimy)).round() #self.data=(50*np.random.rand(self.dimx,self.dimy)).round() + 150 else: if path==None: self.path=self.conf.value(self.name+"/path") self.data=self.OpenF(fileOpen=self.path+'/'+file) self.Display(self.data) def setup(self): # definition of all button TogOff=self.icon+'Toggle_Off.png' TogOn=self.icon+'Toggle_On.png' TogOff=pathlib.Path(TogOff) TogOff=pathlib.PurePosixPath(TogOff) TogOn=pathlib.Path(TogOn) TogOn=pathlib.PurePosixPath(TogOn) self.setStyleSheet("QCheckBox::indicator{width: 30px;height: 30px;}""QCheckBox::indicator:unchecked { image : url(%s);}""QCheckBox::indicator:checked { image: url(%s);}""QCheckBox{font :10pt;}" % (TogOff,TogOn) ) vbox1=QVBoxLayout() self.hbox0=QHBoxLayout() vbox1.addLayout(self.hbox0) hbox1=QHBoxLayout() self.checkBoxPlot=QCheckBox('CROSS',self) self.checkBoxPlot.setChecked(False) self.label_CrossValue=QLabel() self.label_CrossValue.setStyleSheet("font:13pt") hbox1.addWidget(self.checkBoxPlot) hbox1.addWidget(self.label_CrossValue) hbox2=QHBoxLayout() self.label_Cross=QLabel() #self.label_Cross.setMaximumHeight(20) self.label_Cross.setMaximumWidth(170) self.label_Cross. setStyleSheet("font:12pt") hbox2.addWidget(self.label_Cross) vbox1.addLayout(hbox1) vbox1.addLayout(hbox2) self.ZoomLabel=QLabel('Zoom') vbox1.addWidget(self.ZoomLabel) self.checkBoxZoom=QSlider(Qt.Horizontal) self.checkBoxZoom.setMaximumWidth(250) self.checkBoxZoom.setMinimum(0) self.checkBoxZoom.setMaximum(200) self.checkBoxZoom.setValue(0) vbox1.addWidget(self.checkBoxZoom) self.checkBoxScale=QCheckBox('Auto Scale',self) self.checkBoxScale.setChecked(True) self.checkBoxScale.setMaximumWidth(100) self.checkBoxColor=QCheckBox('Color',self) self.checkBoxColor.setChecked(True) self.checkBoxHist=QCheckBox('Hist',self) self.checkBoxHist.setChecked(False) self.maxGraphBox=QCheckBox('Max',self) hbox3=QHBoxLayout() grid_layout = QGridLayout() grid_layout.setVerticalSpacing(0) grid_layout.setHorizontalSpacing(10) grid_layout.addWidget(self.checkBoxScale, 0, 0) grid_layout.addWidget(self.checkBoxColor,1,0) grid_layout.addWidget(self.checkBoxHist, 0, 1) #grid_layout.addWidget(self.checkBoxZoom, 1, 0) grid_layout.addWidget(self.maxGraphBox, 1,1) hbox3.addLayout(grid_layout) vbox1.addLayout(hbox3) hbox4=QHBoxLayout() if self.meas=='on': self.MeasButton=QPushButton('Meas.') hbox4.addWidget(self.MeasButton) vbox1.addLayout(hbox4) vbox1.addStretch(1) self.winImage = pg.GraphicsLayoutWidget() #self.winImage.setContentsMargins(1,1,1,1) self.winImage.setAspectLocked(True) self.winImage.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) #self.winImage.ci.setContentsMargins(1,1,1,1) vbox2=QVBoxLayout() # self.dockImage=QDockWidget(self) # self.dockImage.setWidget(self.winImage) # self.dockImage.setFeatures(QDockWidget.DockWidgetFloatable) #vbox2.addWidget(self.dockImage) vbox2.addWidget(self.winImage) vbox2.setContentsMargins(0,0,0,0) self.p1=self.winImage.addPlot() self.imh=pg.ImageItem() self.axeX=self.p1.getAxis('bottom') self.axeY=self.p1.getAxis('left') self.p1.addItem(self.imh) self.p1.setMouseEnabled(x=False,y=False) self.p1.setContentsMargins(0,0,0,0) self.p1.setAspectLocked(True,ratio=1) self.p1.showAxis('right',show=False) self.p1.showAxis('top',show=False) self.p1.showAxis('left',show=True) self.p1.showAxis('bottom',show=True) if self.bloqKeyboard==True: self.vLine = pg.InfiniteLine(angle=90, movable=False,pen='r') self.hLine = pg.InfiniteLine(angle=0, movable=False,pen='r') else: self.vLine = pg.InfiniteLine(angle=90, movable=False,pen='y') self.hLine = pg.InfiniteLine(angle=0, movable=False,pen='y') self.xc=int(self.conf.value(self.name+"/xc")) self.yc=int(self.conf.value(self.name+"/yc")) self.rx=int(self.conf.value(self.name+"/rx")) self.ry=int(self.conf.value(self.name+"/ry")) self.vLine.setPos(self.xc) self.hLine.setPos(self.yc) self.ro1=pg.EllipseROI([self.xc,self.yc],[self.rx,self.ry],pen='y',movable=False,maxBounds=QtCore.QRectF(0,0,self.rx,self.ry)) self.ro1.setPos([self.xc-(self.rx/2),self.yc-(self.ry/2)]) # text for fwhm on p1 self.textX = pg.TextItem(angle=-90) self.textY = pg.TextItem() #histogram self.hist = pg.HistogramLUTItem() self.hist.setImageItem(self.imh) self.hist.autoHistogramRange() self.hist.gradient.loadPreset('flame') ## XY graph self.curve2=pg.PlotCurveItem() self.curve3=pg.PlotCurveItem() ## main layout hMainLayout=QHBoxLayout() if self.aff=='right': hMainLayout.addLayout(vbox2) hMainLayout.addLayout(vbox1) else : hMainLayout.addLayout(vbox1) hMainLayout.addLayout(vbox2) hMainLayout.setContentsMargins(1,1,1,1) hMainLayout.setSpacing(1) hMainLayout.setStretch(10,1) self.setLayout(hMainLayout) self.setContentsMargins(1,1,1,1) def actionButton(self): # action of button self.checkBoxColor.stateChanged.connect(self.Color) self.checkBoxPlot.stateChanged.connect(self.PlotXY) self.ro1.sigRegionChangeFinished.connect(self.roiChanged) self.checkBoxZoom.valueChanged.connect(self.Zoom) #self.checkBoxZoom.stateChanged.connect(self.Zoom) self.checkBoxHist.stateChanged.connect(self.HIST) self.maxGraphBox.stateChanged.connect(self.Coupe) if self.meas=='on': self.MeasButton.clicked.connect(self.Measurement,QtCore.Qt.DirectConnection) # send data to widget measurement if self.parent is not None : # reveceive data display it self.parent.dataSignal.connect(self.Display)#,QtCore.Qt.DirectConnection) def shortcut(self): # keyboard shortcut self.shortcutPu=QShortcut(QtGui.QKeySequence("+"),self) self.shortcutPu.activated.connect(self.paletteup) self.shortcutPu.setContext(Qt.ShortcutContext(3)) #3: The shortcut is active when its parent widget, or any of its children has focus. default O The shortcut is active when its parent widget has focus. self.shortcutPd=QtGui.QShortcut(QtGui.QKeySequence("-"),self) self.shortcutPd.activated.connect(self.palettedown) self.shortcutPd.setContext(Qt.ShortcutContext(3)) self.shortcutOpen=QtGui.QShortcut(QtGui.QKeySequence("Ctrl+o"),self) self.shortcutOpen.activated.connect(self.OpenF) self.shortcutOpen.setContext(Qt.ShortcutContext(3)) self.shortcutSave=QtGui.QShortcut(QtGui.QKeySequence("Ctrl+s"),self) self.shortcutSave.activated.connect(self.SaveF) self.shortcutSave.setContext(Qt.ShortcutContext(3)) if self.meas=='on': self.shortcutMeas=QtGui.QShortcut(QtGui.QKeySequence('Ctrl+m'),self) self.shortcutMeas.activated.connect(self.Measurement) self.shortcutMeas.setContext(Qt.ShortcutContext(3)) self.shortcutBloq=QtGui.QShortcut(QtGui.QKeySequence("Ctrl+b"),self) self.shortcutBloq.activated.connect(self.bloquer) self.shortcutBloq.setContext(Qt.ShortcutContext(3)) self.shortcutDebloq=QtGui.QShortcut(QtGui.QKeySequence("Ctrl+d"),self) self.shortcutDebloq.activated.connect(self.debloquer) self.shortcutDebloq.setContext(Qt.ShortcutContext(3)) # mousse action: self.proxy=pg.SignalProxy(self.p1.scene().sigMouseMoved, rateLimit=60, slot=self.mouseMoved) self.p1.scene().sigMouseClicked.connect(self.mouseClick) self.vb=self.p1.vb def Measurement(self) : # show widget for measurement on all image or ROI (max, min mean ...) if self.ite=='rect': self.RectChanged() self.winM.setFile(self.nomFichier) self.open_widget(self.winM) self.winM.Display(self.cut) if self.ite=='cercle': self.CercChanged() self.winM.setFile(self.nomFichier) self.open_widget(self.winM) self.winM.Display(self.cut) # if self.ite=='line': # self.LigneChanged() # self.winM.setFile(self.nomFichier) # self.open_widget(self.winM) # self.winM.Display(self.cut) if self.meas=="on": if self.ite==None: self.winM.setFile(self.nomFichier) self.open_widget(self.winM) self.winM.Display(self.data) def Display(self,data): # display the data and refresh all the calculated things and plots self.data=data self.dimy=np.shape(self.data)[1] self.dimx=np.shape(self.data)[0] self.p1.setXRange(0,self.dimx) self.p1.setYRange(0,self.dimy) self.p1.setAspectLocked(True,ratio=1) if self.checkBoxScale.isChecked()==1: # autoscale on self.imh.setImage(self.data.astype(float),autoLevels=True,autoDownsample=True) else : self.imh.setImage(self.data.astype(float),autoLevels=False,autoDownsample=True) if self.meas=="on" : if self.winM.isWinOpen==True: self.newMesurment.emit(self.data)# measurement update #self.Measurement() self.Zoom() # update zoom def mouseClick(self): # block the cross if mousse button clicked if self.bloqq==1: self.bloqq=0 else : self.bloqq=1 self.conf.setValue(self.name+"/xc",int(self.xc)) # save cross postion in ini file self.conf.setValue(self.name+"/yc",int(self.yc)) def mouseMoved(self,evt): ## the cross mouve with the mousse mvt if self.bloqKeyboard==False : #mouse not blocked by keyboard if self.bloqq==0: # mouse not blocked by mouse click pos = evt[0] ## using signal proxy turns original arguments into a tuple if self.p1.sceneBoundingRect().contains(pos): mousePoint = self.vb.mapSceneToView(pos) self.xMouse = (mousePoint.x()) self.yMouse= (mousePoint.y()) if ((self.xMouse>0 and self.xMouse<self.dimx-1) and (self.yMouse>0 and self.yMouse<self.dimy-1) ): self.xc = self.xMouse self.yc= self.yMouse self.vLine.setPos(self.xc) self.hLine.setPos(self.yc) # the cross move only in the graph #self.ro1.setPos([self.xc-(self.rx/2),self.yc-(self.ry/2)]) self.PlotXY() def fwhm(self,x, y, order=3): """ Determine full-with-half-maximum of a peaked set of points, x and y. """ y=gaussian_filter(y,5) # filtre for reducing noise half_max = np.amax(y)/2.0 s = splrep(x, y - half_max,k=order) # F roots = sproot(s) # Given the knots . if len(roots) > 2: pass elif len(roots) < 2: pass else: return np.around(abs(roots[1] - roots[0]),decimals=2) def Coupe(self): # make plot profile on cross if self.maxGraphBox.isChecked()==True and self.bloqKeyboard==False: # find and fix the cross on the maximum of the image dataF=gaussian_filter(self.data,5) (self.xc,self.yc)=pylab.unravel_index(dataF.argmax(),self.data.shape) #take the max ndimage.measurements.center_of_mass(dataF)# self.vLine.setPos(self.xc) self.hLine.setPos(self.yc) dataCross=self.data[int(self.xc),int(self.yc)] coupeX=self.data[int(self.xc),:] coupeY=self.data[:,int(self.yc)] xxx=np.arange(0,int(self.dimx),1)# yyy=np.arange(0,int(self.dimy),1)# coupeXMax=np.max(coupeX) coupeYMax=np.max(coupeY) if coupeXMax==0: # avoid zero coupeXMax=1 if coupeYMax==0: coupeYMax=1 self.label_Cross.setText('x='+ str(int(self.xc)) + ' y=' + str(int(self.yc)) ) dataCross=round(dataCross,3) # take data value on the cross self.label_CrossValue.setText(' v.=' + str(dataCross)) coupeXnorm=(self.data.shape[0]/10)*(coupeX/coupeXMax) # normalize the curves self.curve2.setData(20+self.xminR+coupeXnorm,yyy,clear=True) coupeYnorm=(self.data.shape[1]/10)*(coupeY/coupeYMax) self.curve3.setData(xxx,20+self.yminR+coupeYnorm,clear=True) def PlotXY(self): # plot curves on the graph if self.checkBoxPlot.isChecked()==1: self.p1.addItem(self.vLine, ignoreBounds=False) self.p1.addItem(self.hLine, ignoreBounds=False) self.p1.addItem(self.curve2) self.p1.addItem(self.curve3) self.p1.showAxis('left',show=True) self.p1.showAxis('bottom',show=True) self.p1.addItem(self.textX) self.p1.addItem(self.textY) self.Coupe() else: self.p1.removeItem(self.vLine) self.p1.removeItem(self.hLine) self.p1.removeItem(self.curve2) self.p1.removeItem(self.curve3) self.p1.removeItem(self.textX) self.p1.removeItem(self.textY) self.p1.showAxis('left',show=False) self.p1.showAxis('bottom',show=False) self.p1.removeItem(self.textX) self.p1.removeItem(self.textY) def paletteup(self): # change the color scale levels=self.imh.getLevels() if levels[0]==None: xmax =self.data.max() xmin=self.data.min() else : xmax=levels[1] xmin=levels[0] self.imh.setLevels([xmin, xmax-(xmax- xmin) / 10]) #hist.setImageItem(imh,clear=True) self.hist.setHistogramRange(xmin,xmax) def palettedown(self): levels=self.imh.getLevels() if levels[0]==None: xmax=self.data.max() xmin=self.data.min() else : xmax=levels[1] xmin=levels[0] self.imh.setLevels([xmin, xmax+ (xmax- xmin) / 10]) #hist.setImageItem(imh,clear=True) self.hist.setHistogramRange(xmin,xmax) def Color(self): """ image in colour/n&b """ if self.checkBoxColor.isChecked()==1: self.hist.gradient.loadPreset('flame') else: self.hist.gradient.loadPreset('grey') def Zoom(self): """Zoom function """ self.zo=self.checkBoxZoom.value() # if self.checkBoxPlot.isChecked()==0: # self.xc=self.dimx/2 # self.yc=self.dimy/2 if self.zo<=2: self.zo=0 self.p1.setXRange(0,self.dimx) self.p1.setYRange(0,self.dimy) self.xminR=0 self.yminR=0 self.xmaxR=self.dimx self.ymaxR=self.dimy else: self.xminR=self.xc-(self.dimx-self.xc)*(1-self.zo/200) self.xmaxR=self.xc+(self.dimx-self.xc)*(1-self.zo/200) self.yminR=self.yc-(self.dimy-self.yc)*(1-self.zo/200) self.ymaxR=self.yc+(self.dimy-self.yc)*(1-self.zo/200) if self.xminR<0: self.xminR=0 if self.xmaxR>self.dimx: self.xmaxR=self.dimx if self.yminR<0: self.yminR=0 if self.ymaxR>self.dimy: self.ymaxR=self.dimy self.p1.setXRange(self.xminR,self.xmaxR) self.p1.setYRange(self.yminR,self.ymaxR) self.Coupe() def roiChanged(self): self.rx=self.ro1.size()[0] self.ry=self.ro1.size()[1] self.conf.setValue(self.name+"/rx",int(self.rx)) self.conf.setValue(self.name+"/ry",int(self.ry)) def bloquer(self): # block the cross self.bloqKeyboard=bool(True) self.conf.setValue(self.name+"/xc",int(self.xc))# save cross postion in ini file self.conf.setValue(self.name+"/yc",int(self.yc)) self.conf.setValue(self.name+"/bloqKeyboard",bool(self.bloqKeyboard)) self.vLine.setPen('r') self.hLine.setPen('r') def debloquer(self): # unblock the cross self.bloqKeyboard=bool(False) self.vLine.setPen('y') self.hLine.setPen('y') self.conf.setValue(self.name+"/bloqKeyboard",bool(self.bloqKeyboard)) def HIST(self): #show histogramm if self.checkBoxHist.isChecked()==1: self.winImage.addItem(self.hist) else: self.winImage.removeItem(self.hist) def OpenF(self,fileOpen=False): #open file in txt spe TIFF sif format fileOpen=fileOpen print(fileOpen) print('open') if fileOpen==False: print('ici') chemin=self.conf.value(self.name+"/path") fname=QtGui.QFileDialog.getOpenFileName(self,"Open File",chemin,"Images (*.txt *.spe *.TIFF *.sif *.tif);;Text File(*.txt);;Ropper File (*.SPE);;Andor File(*.sif);; TIFF file(*.TIFF)") fichier=fname[0] else: fichier=str(fileOpen) ext=os.path.splitext(fichier)[1] if ext=='.txt': # text file data=np.loadtxt(str(fichier)) elif ext=='.spe' or ext=='.SPE': # SPE file dataSPE=SpeFile(fichier) data1=dataSPE.data[0]#.transpose() # first frame data=data1#np.flipud(data1) elif ext=='.TIFF' or ext=='.tif':# tiff File dat=Image.open(fichier) data=np.array(dat) elif ext=='.sif': sifop=SifFile() im=sifop.openA(fichier) data=np.rot90(im,3) # self.data=self.data[250:495,:] else : msg = QMessageBox() msg.setIcon(QMessageBox.Critical) msg.setText("Wrong file format !") msg.setInformativeText("The format of the file must be : .SPE .TIFF .sif or .txt ") msg.setWindowTitle("Warning ...") msg.setWindowFlags(QtCore.Qt.WindowStaysOnTopHint) msg.exec_() chemin=os.path.dirname(fichier) self.conf.setValue(self.name+"/path",chemin) self.conf.setValue(self.name+"/lastFichier",os.path.split(fichier)[1]) self.fileName.setText(os.path.split(fichier)[1]) self.nomFichier=os.path.split(fichier)[1] self.newDataReceived(data) def SaveF (self): # save data in TIFF if self.tiff==True: fname=QtGui.QFileDialog.getSaveFileName(self,"Save data as TIFF",self.path) self.path=os.path.dirname(str(fname[0])) fichier=fname[0] ext=os.path.splitext(fichier)[1] #print(ext) print(fichier,' is saved') self.conf.setValue(self.name+"/path",self.path) time.sleep(0.1) img_PIL = Image.fromarray(self.data) img_PIL.save(str(fname[0])+'.TIFF',format='TIFF') else : fname=QtGui.QFileDialog.getSaveFileName(self,"Save data as txt",self.path) self.path=os.path.dirname(str(fname[0])) fichier=fname[0] ext=os.path.splitext(fichier)[1] #print(ext) print(fichier,' is saved') self.conf.setValue(self.name+"/path",self.path) time.sleep(0.1) np.savetxt(str(fichier)+'.txt',self.data) def newDataReceived(self,data): # Do display and save origin data when new data is sent to visu self.data=data self.dimy=np.shape(self.data)[1] self.dimx=np.shape(self.data)[0] #self.Display(self.data) self.dataSignal.emit(self.data) def open_widget(self,fene): """ open new widget """ if fene.isWinOpen==False: fene.setup fene.isWinOpen=True #fene.Display(self.data) fene.show() else: #fene.activateWindow() fene.raise_() fene.showNormal() def closeEvent(self,event): # when the window is closed if self.winM.isWinOpen==True: self.winM.close()
def initUI(self): self.setGeometry(300, 300, 1200, 600) self.setWindowTitle('CrossCobra - Python IDE') # splitters splitter1 = QSplitter(Qt.Vertical) splitter2 = QSplitter(Qt.Horizontal) # widgets self.notebook = TabWidget(self) self.codeView = CodeView(self, self.notebook) self.notebook.newTab(codeView=self.codeView) self.textPad = self.notebook.textPad self.fileBrowser = FileBrowser(self, self.textPad, self.notebook, self.codeView) self.textPad.fileBrowser = self.fileBrowser # add widgets to splitters splitter1.addWidget(self.fileBrowser) splitter1.addWidget(self.codeView) w = splitter1.width() splitter1.setSizes([w//2, w//2]) splitter2.addWidget(splitter1) splitter2.addWidget(self.notebook) hbox = QHBoxLayout() hbox.addWidget(splitter2) splitter1.setStretchFactor(1, 1) splitter2.setStretchFactor(1, 10) self.setCentralWidget(splitter2) # actions newAction = QAction(QIcon(self.HOME + 'images/new.png'), 'New', self) newAction.setShortcut('Ctrl+N') newAction.triggered.connect(self.new) openAction = QAction(QIcon(self.HOME + 'images/open.png'), 'Open', self) openAction.setShortcut('Ctrl+O') openAction.triggered.connect(self.open) saveAction = QAction(QIcon(self.HOME + 'images/save.png'), 'Save', self) saveAction.setShortcut('Ctrl+S') saveAction.triggered.connect(self.save) saveAsAction = QAction(QIcon(self.HOME + 'images/saveAs.png'), 'Save As', self) saveAsAction.setShortcut('Ctrl+Shift+S') saveAsAction.triggered.connect(self.saveAs) printAction = QAction(QIcon(self.HOME + 'images/print.png'), 'Print', self) printAction.setShortcut('Ctrl+P') printAction.triggered.connect(self.onPrint) undoAction = QAction(QIcon(self.HOME + 'images/undo.png'), 'Undo', self) undoAction.setShortcut('Ctrl+Z') undoAction.triggered.connect(self.undo) redoAction = QAction(QIcon(self.HOME + 'images/redo.png'), 'Redo', self) redoAction.setShortcut('Ctrl+Shift+Z') redoAction.triggered.connect(self.redo) zoomInAction = QAction(QIcon(self.HOME + 'images/zoomIn.png'), 'ZoomIn', self) zoomInAction.setShortcut('Ctrl++') zoomInAction.triggered.connect(self.zoomIn) zoomOutAction = QAction(QIcon(self.HOME + 'images/zoomOut.png'), 'ZoomOut', self) zoomOutAction.setShortcut('Ctrl+-') zoomOutAction.triggered.connect(self.zoomOut) settingsAction = QAction(QIcon(self.HOME + 'images/settings.png'), 'Settings', self) settingsAction.setShortcut('F9') settingsAction.triggered.connect(self.showSettings) interpreterAction = QAction(QIcon(self.HOME + 'images/interpreter.png'), 'Start Python Interpreter', self) interpreterAction.setShortcut('F10') interpreterAction.triggered.connect(self.interpreter) terminalAction = QAction(QIcon(self.HOME + 'images/terminal.png'), 'Start Terminal', self) terminalAction.setShortcut('F11') terminalAction.triggered.connect(self.terminal) runAction = QAction(QIcon(self.HOME + 'images/run.png'), 'Run File', self) runAction.setShortcut('F12') runAction.triggered.connect(self.run) searchShortcut = QShortcut(self) searchShortcut.setKey('Ctrl+F') searchShortcut.activated.connect(self.onSearch) spacer = QWidget() spacer.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) # make toolbar self.toolbar = QToolBar() self.toolbar.setStyleSheet(''' QToolButton::hover { background-color: darkgreen;} ''') self.toolbar.setContextMenuPolicy(Qt.PreventContextMenu) self.addToolBar(Qt.RightToolBarArea, self.toolbar) self.toolbar.addSeparator() self.toolbar.addAction(newAction) self.toolbar.addSeparator() self.toolbar.addAction(openAction) self.toolbar.addSeparator() self.toolbar.addAction(saveAction) self.toolbar.addSeparator() self.toolbar.addAction(saveAsAction) self.toolbar.addSeparator() self.toolbar.addAction(printAction) self.toolbar.addSeparator() self.toolbar.addAction(undoAction) self.toolbar.addSeparator() self.toolbar.addAction(redoAction) self.toolbar.addSeparator() self.toolbar.addAction(zoomInAction) self.toolbar.addSeparator() self.toolbar.addAction(zoomOutAction) self.toolbar.addSeparator() self.toolbar.addAction(settingsAction) self.toolbar.addSeparator() self.toolbar.addWidget(spacer) self.toolbar.addAction(interpreterAction) self.toolbar.addSeparator() self.toolbar.addAction(terminalAction) self.toolbar.addSeparator() self.toolbar.addAction(runAction) # make statusbar self.statusBar = QStatusBar() self.searchEdit = QLineEdit() spacer2 = QWidget() self.searchEdit.setStyleSheet( ''' background-color: white; color: black; ''') self.searchEdit.returnPressed.connect(self.onSearch) self.searchButton = QPushButton(QIcon(self.HOME + 'images/search.png'), 'Search', self) self.searchButton.setStyleSheet( ''' QPushButton::hover { background-color: darkgreen;} ''') self.searchButton.clicked.connect(self.onSearch) self.statusBar.addPermanentWidget(spacer2) self.statusBar.addPermanentWidget(self.searchEdit) self.statusBar.addPermanentWidget(self.searchButton) self.setStatusBar(self.statusBar) # show all self.textPad.setFocus() self.show()
def create_app(self): self.layout = QVBoxLayout() self.layout.setSpacing(0) self.layout.setContentsMargins(0, 0, 0, 0) # Create Tabs self.tabbar = QTabBar(movable=True, tabsClosable=True) self.tabbar.tabCloseRequested.connect(self.close_tab) self.tabbar.tabBarClicked.connect(self.switch_tab) self.tabbar.setCurrentIndex(0) self.tabbar.setDrawBase(False) self.tabbar.setLayoutDirection(Qt.LeftToRight) self.tabbar.setElideMode(Qt.ElideLeft) self.shortcut_new_tab = QShortcut(QKeySequence("Ctrl+T"), self) self.shortcut_new_tab.activated.connect(self.add_tab) self.shortcut_reload = QShortcut(QKeySequence("Ctrl+R"), self) self.shortcut_reload.activated.connect(self.reload_page) # Keep track of tabs self.tab_count = 0 self.tabs = [] # Create Address Bar self.toolbar = QWidget() self.toolbar.setObjectName("toolbar") self.toolbar_layout = QHBoxLayout() self.addressbar = AddressBar() self.add_tab_button = QPushButton("+") # Connect AdressBar + button Signals self.addressbar.returnPressed.connect(self.browse_to) self.add_tab_button.clicked.connect(self.add_tab) # Set toolbar buttons self.back_button = QPushButton("<") self.back_button.clicked.connect(self.go_back) self.forward_button = QPushButton(">") self.forward_button.clicked.connect(self.go_forward) self.reload_button = QPushButton("R") self.reload_button.clicked.connect(self.reload_page) # Build toolbar self.toolbar.setLayout(self.toolbar_layout) self.toolbar_layout.addWidget(self.back_button) self.toolbar_layout.addWidget(self.reload_button) self.toolbar_layout.addWidget(self.forward_button) self.toolbar_layout.addWidget(self.addressbar) self.toolbar_layout.addWidget(self.add_tab_button) # Set main view self.container = QWidget() self.container.layout = QStackedLayout() self.container.setLayout(self.container.layout) self.layout.addWidget(self.tabbar) self.layout.addWidget(self.toolbar) self.layout.addWidget(self.container) self.setLayout(self.layout) self.add_tab() self.show()
def __init__(self): super().__init__() # map keyboard shortcuts for key in settings.keyboardshortcut.get('Home', '').split('|'): QShortcut(self.getQKeySequence(key), self, self.key_home) for key in settings.keyboardshortcut.get('Backspace', '').split('|'): QShortcut(self.getQKeySequence(key), self, self.key_backspace) for key in settings.keyboardshortcut.get('Enter', '').split('|'): QShortcut(self.getQKeySequence(key), self, self.key_enter) for key in settings.keyboardshortcut.get('PageUp', '').split('|'): QShortcut(self.getQKeySequence(key), self, self.key_pageup) for key in settings.keyboardshortcut.get('PageDown', '').split('|'): QShortcut(self.getQKeySequence(key), self, self.key_pagedown) for key in settings.keyboardshortcut.get('F1', '').split('|'): QShortcut(self.getQKeySequence(key), self, self.key_F1) for key in settings.keyboardshortcut.get('F2', '').split('|'): QShortcut(self.getQKeySequence(key), self, self.key_F2) for key in settings.keyboardshortcut.get('F3', '').split('|'): QShortcut(self.getQKeySequence(key), self, self.key_F3) for key in settings.keyboardshortcut.get('F4', '').split('|'): QShortcut(self.getQKeySequence(key), self, self.key_F4) for key in settings.keyboardshortcut.get('switchchannel', '').split('|'): QShortcut(self.getQKeySequence(key), self, playlist.switchChannel) for key in settings.keyboardshortcut.get('playnextsong', '').split('|'): QShortcut(self.getQKeySequence(key), self, playlist.playNextSong) for key in settings.keyboardshortcut.get('pitchup', '').split('|'): QShortcut(self.getQKeySequence(key), self, playlist.setPitchUp) for key in settings.keyboardshortcut.get('pitchflat', '').split('|'): QShortcut(self.getQKeySequence(key), self, playlist.setPitchFlat) for key in settings.keyboardshortcut.get('pitchdown', '').split('|'): QShortcut(self.getQKeySequence(key), self, playlist.setPitchDown) for key in settings.keyboardshortcut.get('jumpforward', '').split('|'): QShortcut(self.getQKeySequence(key), self, playlist.jumpForward).setAutoRepeat(True) for key in settings.keyboardshortcut.get('jumpbackward', '').split('|'): QShortcut(self.getQKeySequence(key), self, playlist.jumpBackward).setAutoRepeat(True) for key in settings.keyboardshortcut.get('playpause', '').split('|'): QShortcut(self.getQKeySequence(key), self, playlist.playpause)
class LoggerTab(*LoggerTabBase): def __init__(self, name, tab_closed_signal, log, loop, main_window, parent_widget): super().__init__() self.log = log.getChild(name) self.log.debug(f'Starting a logger named {name}') self.name = name self.main_window = main_window self.parent_widget = parent_widget self.loop = loop self.level_filter = LevelFilter() self.level_filter.set_all_pass(False) self.filter_model_enabled = True self.detail_model = DetailTableModel() self.namespace_tree_model = LogNamespaceTreeModel() self.popped_out = False self.autoscroll = True self.scroll_max = 0 self.record_count = 0 self.monitor_count = 0 # for monitoring self.tab_closed_signal = tab_closed_signal self.last_status_update_time = 0 self.search_bar_visible = CONFIG['search_open_default'] self.search_regex = CONFIG['search_regex_default'] self.search_casesensitive = CONFIG['search_casesensitive_default'] self.search_wildcard = CONFIG['search_wildcard_default'] self.search_start = 0 self.search_filter = False self.setupUi() def setupUi(self): super().setupUi(self.parent_widget) self.table_header = LoggerTableHeader( self.loggerTable.horizontalHeader()) self.record_model = LogRecordModel(self, self.level_filter.levels, self.table_header) self.createLevelButton.clicked.connect(self.create_level) self.loggerTable.setMouseTracking(False) self.loggerTable.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.loggerTable.verticalScrollBar().rangeChanged.connect( self.onRangeChanged) self.loggerTable.verticalScrollBar().valueChanged.connect( self.onScroll) self.loggerTable.setContextMenuPolicy(Qt.CustomContextMenu) self.loggerTable.customContextMenuRequested.connect( self.open_logger_table_menu) self.loggerTable.setStyleSheet("QTableView { border: 0px;}") self.loggerTable.verticalHeader().setDefaultSectionSize( CONFIG['logger_row_height']) self.namespaceTreeView.setModel(self.namespace_tree_model) self.namespaceTreeView.selectionModel().selectionChanged.connect( self.reset_master) self.namespaceTreeView.setContextMenuPolicy(Qt.CustomContextMenu) self.namespaceTreeView.customContextMenuRequested.connect( self.open_namespace_table_menu) self.namespace_tree_model.rowsInserted.connect( self.on_tree_rows_inserted) for levelno, level in self.level_filter.levels.items(): self.add_level_to_table(level) self.levelsTable.doubleClicked.connect(self.level_double_clicked) self.levelsTable.installEventFilter(self) self.levelsTable.setContextMenuPolicy(Qt.CustomContextMenu) self.levelsTable.customContextMenuRequested.connect( self.open_levels_table_menu) if self.filter_model_enabled: self.filter_model = RecordFilter(self, self.namespaceTreeView, self.level_filter) self.filter_model.setSourceModel(self.record_model) self.loggerTable.setModel(self.filter_model) else: self.loggerTable.setModel(self.record_model) self.loggerTable.selectionModel().selectionChanged.connect( self.update_detail) self.detailTable.setModel(self.detail_model) self.table_header_view = header = self.loggerTable.horizontalHeader() header.setStretchLastSection(True) # header.sectionResized.connect(self.table_header.column_resized) header.viewport().installEventFilter( self.table_header) # read the docstring header.setContextMenuPolicy(Qt.CustomContextMenu) header.customContextMenuRequested.connect(self.open_header_menu) self.searchSC = QShortcut('Ctrl+F', self.parent_widget) self.searchSC.activated.connect(self.toggle_search) self.searchSC.setAutoRepeat(False) self.searchSC_F3 = QShortcut('F3', self.parent_widget) self.searchSC_F3.activated.connect(self.search_down_or_close) self.searchSC_F3.setAutoRepeat(True) self.searchSC_Esc = QShortcut('Esc', self.parent_widget) self.searchSC_Esc.activated.connect( partial(self.set_search_visible, False)) self.searchSC_Esc.setAutoRepeat(False) self.searchLine.returnPressed.connect(self.search_down) self.searchDownButton.clicked.connect(self.search_down) self.searchDownButton.setMenu(self.setup_search_button_menu()) self.searchWidget.setVisible(self.search_bar_visible) self.filterButton.clicked.connect(self.filter_or_clear) self.filterButton.setToolTip( 'Adheres to the same settings as the search') # @NextVersion: make this happen self.levelButtonsLayout.setParent(None) self.createLevelButton.setVisible(False) self.presetsButton.setVisible(False) self.setup_internal_connections() self.set_columns_sizes() def setup_search_button_menu(self): smenu = QMenu(self.searchDownButton) action_regex = smenu.addAction('Regex') action_regex.setCheckable(True) action_regex.setChecked(self.search_regex) action_regex.triggered.connect(partial(setattr, self, 'search_regex')) action_case = smenu.addAction('Case sensitive') action_case.setCheckable(True) action_case.setChecked(self.search_casesensitive) action_case.triggered.connect( partial(setattr, self, 'search_casesensitive')) action_wild = smenu.addAction('Wildcard') action_wild.setCheckable(True) action_wild.setChecked(self.search_wildcard) action_wild.triggered.connect(partial(setattr, self, 'search_wildcard')) return smenu def setup_internal_connections(self): CONFIG.row_height_changed.connect(self.row_height_changed) def filter_or_clear(self): self.search_filter = not self.search_filter if self.search_filter: self.filterButton.setText('Clear filter') self.filter_model.search_filter = True self.filter_model.set_filter(self.searchLine.text(), self.search_regex, self.search_wildcard, self.search_casesensitive) else: self.filterButton.setText('Filter') self.filter_model.clear_filter() def set_columns_sizes(self): # self.table_header.ignore_resizing = True cols = self.table_header.visible_columns for i, col in enumerate(cols): self.table_header_view.resizeSection(i, col.width) # self.table_header.ignore_resizing = False def set_max_capacity(self, max_capacity): self.record_model.max_capacity = max_capacity self.record_model.trim_if_needed() def header_section_resized(self, index, oldw, neww): if index == 4: return self.log.warn(f"index = {index}, {oldw} -> {neww}") def eventFilter(self, object, event): if event.type() == QEvent.KeyPress: if event.key() == Qt.Key_Space or event.key() == Qt.Key_Return: self.toggle_selected_levels() return True return False def toggle_selected_levels(self): selected = self.levelsTable.selectedIndexes() for index in selected: if index.column() == 0: checkbox = self.levelsTable.cellWidget( index.row(), index.column()).children()[1] checkbox.toggle() self.reset_master() def search_down(self): start = self.filter_model.index(self.search_start, 0, INVALID_INDEX) s = self.searchLine.text() if not self.search_regex: search_flags = Qt.MatchContains else: search_flags = Qt.MatchRegExp if self.search_casesensitive: search_flags = search_flags | Qt.MatchCaseSensitive if self.search_wildcard: search_flags = search_flags | Qt.MatchWildcard hits = self.filter_model.match(start, SearchRole, s, 1, Qt.MatchWrap | search_flags) if not hits: self.log.warn(f'No matches for {s}') self.search_start = 0 else: result = hits[0] self.search_start = result.row() + 1 self.loggerTable.scrollTo(result) self.loggerTable.setCurrentIndex(result) def search_down_or_close(self): if self.search_bar_visible is False: self.set_search_visible(True) elif self.searchLine.text() == "": self.set_search_visible(False) else: self.search_down() def set_search_visible(self, visible): self.search_bar_visible = visible self.searchWidget.setVisible(self.search_bar_visible) if self.search_bar_visible: self.searchLine.setFocus() else: self.searchLine.clear() def toggle_search(self): self.search_bar_visible = not self.search_bar_visible self.set_search_visible(self.search_bar_visible) def on_record(self, record): level = self.process_level(record.levelno, record.levelname) record.levelname = level.levelname self.record_model.add_record(record) if self.autoscroll: self.loggerTable.scrollToBottom() self.register_logger(record.name) self.record_count += 1 self.monitor_count += 1 # self.loggerTable.resizeRowsToContents() def get_record(self, index): if self.filter_model_enabled: source_index = self.filter_model.mapToSource(index) record = self.record_model.get_record(source_index) else: record = self.record_model.get_record(index) return record def register_logger(self, name): self.namespace_tree_model.register_logger(name) def process_level(self, levelno, levelname): level = self.level_filter.levels.get(levelno) if level: level.msg_count += 1 return level new_level = LogLevel(levelno, levelname) self.level_filter.add_level(new_level) self.add_level_to_table(new_level) return new_level def add_level_to_table(self, level): row_count = self.levelsTable.rowCount() self.levelsTable.setRowCount(row_count + 1) checkbox = QCheckBox() checkbox.setStyleSheet( "QCheckBox::indicator { width: 15px; height: 15px;}") checkbox.toggle() checkbox.clicked.connect(level.set_enabled) checkbox.clicked.connect(self.reset_master) checkbox.toggled.connect(level.set_enabled) checkbox_layout = QHBoxLayout() checkbox_layout.setAlignment(Qt.AlignCenter) checkbox_layout.setContentsMargins(0, 0, 0, 0) checkbox_layout.addWidget(checkbox) checkbox_widget = QWidget() checkbox_widget.setLayout(checkbox_layout) checkbox_widget.setStyleSheet("QWidget { background-color:none;}") self.levelsTable.setCellWidget(row_count, 0, checkbox_widget) self.levelsTable.setItem(row_count, 1, QTableWidgetItem(str(level.levelno))) self.levelsTable.setItem(row_count, 2, QTableWidgetItem(level.levelname)) self.levelsTable.sortItems(1, Qt.SortOrder(Qt.AscendingOrder)) self.levelsTable.resizeColumnToContents(1) def open_namespace_table_menu(self, position): menu = QMenu(self) include_children_action = menu.addAction("Selection includes children") include_children_action.setCheckable(True) if self.filter_model_enabled: include_children_action.setChecked( self.filter_model.selection_includes_children) else: include_children_action.set_enabled(False) include_children_action.triggered.connect( self.toggle_selection_includes_children) menu.popup(self.namespaceTreeView.viewport().mapToGlobal(position)) def toggle_selection_includes_children(self, val): self.filter_model.selection_includes_children = val self.reset_master() def open_levels_table_menu(self, position): menu = QMenu(self) enable_all_action = menu.addAction("Enable all") enable_all_action.triggered.connect(self.enable_all_levels) disable_all_action = menu.addAction("Disable all") disable_all_action.triggered.connect(self.disable_all_levels) menu.addSeparator() edit_action = menu.addAction("Edit selected level") edit_action.triggered.connect(self.open_edit_level_dialog) menu.popup(self.levelsTable.viewport().mapToGlobal(position)) def open_logger_table_menu(self, position): # Needed as a workaround for when the header column count is 0 and it becomes invisible if self.table_header.column_count == 0: self.open_header_menu(position) return selected = self.loggerTable.selectedIndexes() if not selected: return row_index = selected[0] record = self.get_record(row_index) menu = QMenu(self) view_message = menu.addAction("View message") view_message.triggered.connect( partial(self.open_text_view_dialog, row_index, False)) if record.exc_text: view_traceback = menu.addAction("View traceback") view_traceback.triggered.connect( partial(self.open_text_view_dialog, row_index, True)) menu.popup(self.table_header_view.viewport().mapToGlobal(position)) def open_header_menu(self, position): menu = QMenu(self) customize_header = menu.addAction("Customize header") customize_header.triggered.connect(self.open_header_dialog) reset_header_action = menu.addAction("Reset header") reset_header_action.triggered.connect(self.table_header.reset_columns) reset_header_action.triggered.connect(self.set_columns_sizes) menu.popup(self.table_header_view.viewport().mapToGlobal(position)) def open_header_dialog(self): d = HeaderEditDialog(self.main_window, self.table_header.columns) d.header_changed.connect(self.header_changed) d.setWindowTitle('Header editor') d.open() def header_changed(self, action, data): if action == 'rearrange': self.table_header.replace_columns(data) elif action == 'load': loaded = CONFIG.load_columns_preset(data) self.table_header.replace_columns(loaded) elif action == 'save': CONFIG.save_columns_preset(data, self) elif action == 'save new': pass self.set_columns_sizes() def merge_with_records(self, new_records): self.record_model.merge_with_records(new_records) for record in new_records: self.register_logger(record.name) level = self.process_level(record.levelno, record.levelname) record.levelname = level.levelname def update_detail(self, sel, desel): indexes = sel.indexes() if len(indexes) <= 0: self.detail_model.clear() return index = indexes[0] record = self.get_record(index) self.detail_model.set_record(record) def open_text_view_dialog(self, index, exception=False): record = self.get_record(index) d = TextViewDialog(self.main_window, record.exc_text if exception else record.message) d.setWindowModality(Qt.NonModal) d.setAttribute(Qt.WA_DeleteOnClose, True) d.setWindowTitle( 'Exception traceback' if exception else 'View message') d.open() def enable_all_levels(self): for row in range(self.levelsTable.rowCount()): checkbox = self.levelsTable.cellWidget(row, 0).children()[1] if not checkbox.isChecked(): checkbox.setChecked(True) self.reset_master() def disable_all_levels(self): for row in range(self.levelsTable.rowCount()): checkbox = self.levelsTable.cellWidget(row, 0).children()[1] if checkbox.isChecked(): checkbox.setChecked(False) self.reset_master() def set_dark_theme(self, value): self.record_model.dark_theme = value def level_double_clicked(self, index): row, column = index.row(), index.column() if column == 0: # if you're clicking at the checkbox widget, just toggle it instead checkbox = self.levelsTable.cellWidget(row, column).children()[1] checkbox.toggle() self.reset_master() else: self.open_edit_level_dialog(row) def open_edit_level_dialog(self, row=None): if not row: selected = self.levelsTable.selectedIndexes() if not selected: return row = selected[0].row() levelno = self.levelsTable.item(row, 1).data(Qt.DisplayRole) level = self.level_filter.levels[int(levelno)] d = LevelEditDialog(self.main_window, level) d.setWindowModality(Qt.NonModal) d.setWindowTitle('Level editor') d.open() def create_level(self): self.log.warn('Creating level') d = LevelEditDialog(creating_new_level=True) d.setWindowModality(Qt.NonModal) d.setWindowTitle('Level editor') d.open() def reset_master(self, sel=None, desel=None): self.record_model.beginResetModel() self.record_model.endResetModel() if self.autoscroll: self.loggerTable.scrollToBottom() def onScroll(self, pos): if pos < self.scroll_max: self.autoscroll = False else: self.autoscroll = True def on_tree_rows_inserted(self, pindex, start, end): tree = self.namespaceTreeView tmodel = self.namespace_tree_model tree.expand(pindex) while start <= end: index = tmodel.index(start, 0, pindex) if not index.isValid(): self.log.error('Invalid index!') else: tree.expand(index) start += 1 def onRangeChanged(self, min, max): self.scroll_max = max def closeEvent(self, event=None): self.log.debug('Tab close event!') self.tab_closed_signal.set() if self.popped_out: self.main_window.close_popped_out_logger(self) def row_height_changed(self, new_height): self.loggerTable.verticalHeader().setDefaultSectionSize(new_height) async def monitor(self): "Used only when benchmark parameter of LogServer is True" records = [] while True: await asyncio.sleep(0.5) status = f"{self.monitor_count * 2} rows/s" if self.monitor_count == 0: break records.append(self.monitor_count) print(status, int(sum(records) / len(records)) * 2, 'average') self.main_window.set_status(status) self.monitor_count = 0 print('Result:', int(sum(records) / len(records)) * 2, 'average')
def __init__(self): QWidget.__init__(self) logger.info("Starting %s" % nw.__package__) logger.debug("Initialising GUI ...") self.mainConf = nw.CONFIG self.theTheme = Theme(self) self.theProject = NWProject(self) self.theIndex = NWIndex(self.theProject, self) self.hasProject = False logger.info("Qt5 Version: %s (%d)" % (self.mainConf.verQtString, self.mainConf.verQtValue)) logger.info("PyQt5 Version: %s (%d)" % (self.mainConf.verPyQtString, self.mainConf.verPyQtValue)) self.resize(*self.mainConf.winGeometry) self._setWindowTitle() self.setWindowIcon(QIcon(path.join(self.mainConf.appIcon))) # Main GUI Elements self.statusBar = GuiMainStatus(self) self.docEditor = GuiDocEditor(self, self.theProject) self.docViewer = GuiDocViewer(self, self.theProject) self.docDetails = GuiDocDetails(self, self.theProject) self.treeView = GuiDocTree(self, self.theProject) self.mainMenu = GuiMainMenu(self, self.theProject) # Minor Gui Elements self.statusIcons = [] self.importIcons = [] # Assemble Main Window self.treePane = QFrame() self.treeBox = QVBoxLayout() self.treeBox.addWidget(self.treeView) self.treeBox.addWidget(self.docDetails) self.treePane.setLayout(self.treeBox) self.splitView = QSplitter(Qt.Horizontal) self.splitView.addWidget(self.docEditor) self.splitView.addWidget(self.docViewer) self.splitView.splitterMoved.connect(self._splitViewMove) self.splitMain = QSplitter(Qt.Horizontal) self.splitMain.addWidget(self.treePane) self.splitMain.addWidget(self.splitView) self.splitMain.setSizes(self.mainConf.mainPanePos) self.splitMain.splitterMoved.connect(self._splitMainMove) self.setCentralWidget(self.splitMain) self.idxTree = self.splitMain.indexOf(self.treePane) self.idxMain = self.splitMain.indexOf(self.splitView) self.idxEditor = self.splitView.indexOf(self.docEditor) self.idxViewer = self.splitView.indexOf(self.docViewer) self.splitMain.setCollapsible(self.idxTree, False) self.splitMain.setCollapsible(self.idxMain, False) self.splitView.setCollapsible(self.idxEditor, False) self.splitView.setCollapsible(self.idxViewer, True) self.docViewer.setVisible(False) # Build The Tree View self.treeView.itemSelectionChanged.connect(self._treeSingleClick) self.treeView.itemDoubleClicked.connect(self._treeDoubleClick) self.rebuildTree() # Set Main Window Elements self.setMenuBar(self.mainMenu) self.setStatusBar(self.statusBar) self.statusBar.setStatus("Ready") # Set Up Autosaving Project Timer self.asProjTimer = QTimer() self.asProjTimer.timeout.connect(self._autoSaveProject) # Set Up Autosaving Document Timer self.asDocTimer = QTimer() self.asDocTimer.timeout.connect(self._autoSaveDocument) # Keyboard Shortcuts QShortcut(Qt.Key_Return, self.treeView, context=Qt.WidgetShortcut, activated=self._treeKeyPressReturn) # Forward Functions self.setStatus = self.statusBar.setStatus self.setProjectStatus = self.statusBar.setProjectStatus if self.mainConf.showGUI: self.show() self.initMain() self.asProjTimer.start() self.asDocTimer.start() self.statusBar.clearStatus() logger.debug("GUI initialisation complete") return
def __init__(self, parent=None): super().__init__() self.setupUi(self) self.setWindowTitle(APP_NAME) self.app = parent self.current_profile = BackupProfileModel.select().order_by( 'id').first() self.setWindowFlags(QtCore.Qt.WindowCloseButtonHint | QtCore.Qt.WindowMinimizeButtonHint) # Load tab models self.repoTab = RepoTab(self.repoTabSlot) self.sourceTab = SourceTab(self.sourceTabSlot) self.archiveTab = ArchiveTab(self.archiveTabSlot) self.scheduleTab = ScheduleTab(self.scheduleTabSlot) self.miscTabSlot = MiscTab(self.miscTabSlot) self.tabWidget.setCurrentIndex(0) self.repoTab.repo_changed.connect( self.archiveTab.populate_from_profile) self.repoTab.repo_added.connect(self.archiveTab.list_action) self.tabWidget.currentChanged.connect( self.scheduleTab._draw_next_scheduled_backup) self.createStartBtn.clicked.connect(self.app.create_backup_action) self.cancelButton.clicked.connect(self.app.backup_cancelled_event.emit) QShortcut(QKeySequence("Ctrl+W"), self).activated.connect(self.on_close_window) QShortcut(QKeySequence("Ctrl+Q"), self).activated.connect(self.on_close_window) self.app.backup_started_event.connect(self.backup_started_event) self.app.backup_finished_event.connect(self.backup_finished_event) self.app.backup_log_event.connect(self.set_status) self.app.backup_cancelled_event.connect(self.backup_cancelled_event) # Init profile list self.profileSelector.addItem('+ Add New Profile', None) self.profileSelector.insertSeparator(2) for profile in BackupProfileModel.select(): self.profileSelector.addItem(profile.name, profile.id) self.profileSelector.setCurrentIndex(2) self.profileSelector.currentIndexChanged.connect( self.profile_select_action) self.profileRenameButton.clicked.connect(self.profile_rename_action) self.profileDeleteButton.clicked.connect(self.profile_delete_action) # OS-specific startup options: if sys.platform != 'darwin': # Hide Wifi-rule section in schedule tab. self.scheduleTab.wifiListLabel.hide() self.scheduleTab.wifiListWidget.hide() self.scheduleTab.page_2.hide() self.scheduleTab.toolBox.removeItem(1) # Connect to existing thread. if BorgThread.is_running(): self.createStartBtn.setEnabled(False) self.cancelButton.setEnabled(True) self.set_status('Backup in progress.', progress_max=0)
def make_shortcut(self): shortcut = QShortcut(QKeySequence(Qt.CTRL + Qt.Key_L), self) shortcut.setContext(Qt.WindowShortcut) shortcut.activated.connect(self.controller.show_location_toolbar) def show_filter(): self.file_filter.setFocus(Qt.ShortcutFocusReason) self.filter_toolbar.show() shortcut = QShortcut(QKeySequence(Qt.CTRL + Qt.Key_K), self) shortcut.setContext(Qt.WindowShortcut) shortcut.activated.connect(show_filter) shortcut = QShortcut(QKeySequence(Qt.Key_F3), self) shortcut.setContext(Qt.WindowShortcut) shortcut.activated.connect(self.controller.show_search) shortcut = QShortcut(QKeySequence(Qt.CTRL + Qt.Key_F), self) shortcut.setContext(Qt.WindowShortcut) shortcut.activated.connect(self.controller.show_search) shortcut = QShortcut(QKeySequence(Qt.CTRL + Qt.Key_W), self) shortcut.setContext(Qt.WindowShortcut) shortcut.activated.connect(self.controller.close_window) shortcut = QShortcut(QKeySequence(Qt.ALT + Qt.Key_Up), self) shortcut.setContext(Qt.WindowShortcut) shortcut.activated.connect(self.controller.parent_directory) shortcut = QShortcut(Qt.Key_Home, self) shortcut.setContext(Qt.WindowShortcut) shortcut.activated.connect(lambda: self.file_view.ensureVisible(0, 0, 1, 1)) shortcut = QShortcut(Qt.Key_End, self) shortcut.setContext(Qt.WindowShortcut) shortcut.activated.connect( lambda: self.file_view.ensureVisible( 0, self.file_view._layout.get_bounding_rect().height(), 1, 1)) shortcut = QShortcut(Qt.Key_PageUp, self) shortcut.setContext(Qt.WindowShortcut) shortcut.activated.connect(lambda: self.file_view.scroll_by(0, -self.file_view.viewport().height())) shortcut = QShortcut(Qt.Key_PageDown, self) shortcut.setContext(Qt.WindowShortcut) shortcut.activated.connect(lambda: self.file_view.scroll_by(0, self.file_view.viewport().height()))
def __init__(self, aPath, parent=None): super(VideoPlayer, self).__init__(parent) #self.setAttribute(Qt.WA_NoSystemBackground, True) self.colorDialog = None self.mediaPlayer = QMediaPlayer(None, QMediaPlayer.VideoSurface) self.mediaPlayer.setVolume(80) self.videoWidget = QVideoWidget(self) self.lbl = QLineEdit('00:00:00') self.lbl.setReadOnly(True) self.lbl.setEnabled(False) self.lbl.setFixedWidth(60) self.lbl.setUpdatesEnabled(True) #self.lbl.setStyleSheet(stylesheet(self)) self.elbl = QLineEdit('00:00:00') self.elbl.setReadOnly(True) self.elbl.setEnabled(False) self.elbl.setFixedWidth(60) self.elbl.setUpdatesEnabled(True) #self.elbl.setStyleSheet(stylesheet(self)) self.playButton = QPushButton() self.playButton.setEnabled(False) self.playButton.setFixedWidth(32) #self.playButton.setStyleSheet("background-color: black") self.playButton.setIcon(self.style().standardIcon(QStyle.SP_MediaPlay)) self.playButton.clicked.connect(self.play) ### pointA button self.apointButton = QPushButton() self.apointButton.setEnabled(False) self.apointButton.setFixedWidth(32) #self.apointButton.setStyleSheet("background-color: black") self.apointButton.setIcon(self.style().standardIcon( QStyle.SP_MediaSeekForward)) self.apointButton.clicked.connect(self.setPointA) ### pointB button self.bpointButton = QPushButton() self.bpointButton.setEnabled(False) self.bpointButton.setFixedWidth(32) #self.bpointButton.setStyleSheet("background-color: black") self.bpointButton.setIcon(self.style().standardIcon( QStyle.SP_MediaSeekBackward)) self.bpointButton.clicked.connect(self.setPointB) ### cut button self.cutButton = QPushButton() self.cutButton.setEnabled(False) self.cutButton.setFixedWidth(32) self.cutButton.setIcon(self.style().standardIcon( QStyle.SP_DriveFDIcon)) self.cutButton.clicked.connect(self.cut) self.positionSlider = QSlider(Qt.Horizontal, self) self.positionSlider.setStyleSheet(stylesheet(self)) self.positionSlider.setRange(0, 100) self.positionSlider.sliderMoved.connect(self.setPosition) self.positionSlider.sliderMoved.connect(self.handle_label) self.positionSlider.setSingleStep(2) self.positionSlider.setPageStep(20) #self.positionSlider.setAttribute(Qt.WA_NoSystemBackground, True) controlLayout = QHBoxLayout() controlLayout.setContentsMargins(5, 0, 5, 0) controlLayout.addWidget(self.playButton) controlLayout.addWidget(self.apointButton) controlLayout.addWidget(self.bpointButton) controlLayout.addWidget(self.cutButton) controlLayout.addWidget(self.lbl) controlLayout.addWidget(self.positionSlider) controlLayout.addWidget(self.elbl) layout0 = QVBoxLayout() layout0.setContentsMargins(0, 0, 0, 0) layout0.addWidget(self.videoWidget) layout0.addLayout(controlLayout) self.setLayout(layout0) self.widescreen = True self.setAcceptDrops(True) self.setWindowTitle("QT5 Player") #self.setWindowFlags(Qt.WindowStaysOnTopHint | Qt.FramelessWindowHint) self.setGeometry(300, 200, 400, 290) self.setContextMenuPolicy(QtCore.Qt.CustomContextMenu) self.customContextMenuRequested[QtCore.QPoint].connect( self.contextMenuRequested) #self.hideSlider() self.show() #self.playFromURL() ### shortcuts ### self.shortcut = QShortcut(QKeySequence('q'), self) self.shortcut.activated.connect(self.handleQuit) self.shortcut = QShortcut(QKeySequence('o'), self) self.shortcut.activated.connect(self.openFile) self.shortcut = QShortcut(QKeySequence(' '), self) self.shortcut.activated.connect(self.play) self.shortcut = QShortcut(QKeySequence('s'), self) self.shortcut.activated.connect(self.toggleSlider) self.shortcut = QShortcut(QKeySequence('v'), self) self.shortcut.activated.connect(self.setPointA) self.shortcut = QShortcut(QKeySequence('b'), self) self.shortcut.activated.connect(self.setPointB) self.shortcut = QShortcut(QKeySequence(Qt.Key_Right), self) self.shortcut.activated.connect(self.forwardSlider) self.shortcut = QShortcut(QKeySequence(Qt.Key_Left), self) self.shortcut.activated.connect(self.backSlider) self.shortcut = QShortcut(QKeySequence(Qt.Key_Up), self) self.shortcut.activated.connect(self.volumeUp) self.shortcut = QShortcut(QKeySequence(Qt.Key_Down), self) self.shortcut.activated.connect(self.volumeDown) self.shortcut = QShortcut( QKeySequence(Qt.ShiftModifier + Qt.Key_Right), self) self.shortcut.activated.connect(self.forwardSlider10) self.shortcut = QShortcut(QKeySequence(Qt.ShiftModifier + Qt.Key_Left), self) self.shortcut.activated.connect(self.backSlider10) self.mediaPlayer.setVideoOutput(self.videoWidget) self.mediaPlayer.stateChanged.connect(self.mediaStateChanged) self.mediaPlayer.positionChanged.connect(self.positionChanged) self.mediaPlayer.positionChanged.connect(self.handle_label) self.mediaPlayer.durationChanged.connect(self.durationChanged) self.mediaPlayer.error.connect(self.handleError) self.apoint = 0 self.bpoint = 0 self.inputfile = pathlib.Path()
def __init__(self, plugin): QFrame.__init__(self, core.workspace()) self._mode = None self.plugin = plugin uic.loadUi(os.path.join(os.path.dirname(__file__), 'SearchWidget.ui'), self) self.cbSearch.setCompleter(None) self.cbReplace.setCompleter(None) self.cbMask.setCompleter(None) self.fsModel = QDirModel(self.cbPath.lineEdit()) self.fsModel.setFilter(QDir.AllDirs | QDir.NoDotAndDotDot) self.cbPath.lineEdit().setCompleter(QCompleter(self.fsModel, self.cbPath.lineEdit())) self._pathBackspaceShortcut = QShortcut(QKeySequence("Ctrl+Backspace"), self.cbPath, self._onPathBackspace) self._pathBackspaceShortcut.setContext(Qt.WidgetWithChildrenShortcut) # TODO QDirModel is deprecated but QCompleter does not yet handle # QFileSystemodel - please update when possible.""" self.cbSearch.setCompleter(None) self.pbSearchStop.setVisible(False) self.pbReplaceCheckedStop.setVisible(False) self._progress = QProgressBar(self) self._progress.setAlignment(Qt.AlignCenter) self._progress.setToolTip(self.tr("Search in progress...")) self._progress.setMaximumSize(QSize(80, 16)) core.mainWindow().statusBar().insertPermanentWidget(1, self._progress) self._progress.setVisible(False) # cd up action self.tbCdUp = QToolButton(self.cbPath.lineEdit()) self.tbCdUp.setIcon(QIcon(":/enkiicons/go-up.png")) self.tbCdUp.setCursor(Qt.ArrowCursor) self.tbCdUp.installEventFilter(self) # for drawing button self.cbSearch.installEventFilter(self) # for catching Tab and Shift+Tab self.cbReplace.installEventFilter(self) # for catching Tab and Shift+Tab self.cbPath.installEventFilter(self) # for catching Tab and Shift+Tab self.cbMask.installEventFilter(self) # for catching Tab and Shift+Tab self._closeShortcut = QShortcut(QKeySequence("Esc"), self) self._closeShortcut.setContext(Qt.WidgetWithChildrenShortcut) self._closeShortcut.activated.connect(self.hide) # connections self.cbSearch.lineEdit().textChanged.connect(self._onSearchRegExpChanged) self.cbSearch.lineEdit().returnPressed.connect(self._onReturnPressed) self.cbReplace.lineEdit().returnPressed.connect(self._onReturnPressed) self.cbPath.lineEdit().returnPressed.connect(self._onReturnPressed) self.cbMask.lineEdit().returnPressed.connect(self._onReturnPressed) self.cbRegularExpression.stateChanged.connect(self._onSearchRegExpChanged) self.cbCaseSensitive.stateChanged.connect(self._onSearchRegExpChanged) self.cbWholeWord.stateChanged.connect(self._onSearchRegExpChanged) self.tbCdUp.clicked.connect(self._onCdUpPressed) self.pbNext.pressed.connect(self.searchNext) self.pbPrevious.pressed.connect(self.searchPrevious) self.pbSearchStop.pressed.connect(self.searchInDirectoryStopPressed) self.pbReplaceCheckedStop.pressed.connect(self.replaceCheckedStopPressed) core.mainWindow().hideAllWindows.connect(self.hide) core.workspace().escPressed.connect(self.hide) core.workspace().currentDocumentChanged.connect( lambda old, new: self.setVisible(self.isVisible() and new is not None))
def initUI(self): self.setObjectName("MainWindow") self.centralwidget = QtWidgets.QWidget(self) self.centralwidget.setObjectName("centralwidget") self.v_box = QVBoxLayout(self.centralwidget) # SET LANGUAGES self.languages = [ [QtWidgets.QLabel(self), QtWidgets.QLineEdit(self)], [QtWidgets.QLabel(self), QtWidgets.QLineEdit(self)], [QtWidgets.QLabel(self), QtWidgets.QLineEdit(self)], [QtWidgets.QLabel(self), QtWidgets.QLineEdit(self)], [QtWidgets.QLabel(self), QtWidgets.QLineEdit(self)] ] self.languages[0][0].setText("German") self.languages[1][0].setText("English") self.languages[2][0].setText("Norwegian") self.languages[3][0].setText("French") self.languages[4][0].setText("Random") # BUTTON self.translate_button = QtWidgets.QPushButton(self) self.translate_button.pressed.connect(self.init_translate) self.translate_button.setText("Translate") self.shortcut_translate = QShortcut(QtGui.QKeySequence('Return'), self) self.shortcut_translate.activated.connect(self.init_translate) self.reset_button = QtWidgets.QPushButton(self) self.reset_button.pressed.connect(self.reset) self.reset_button.setText("Reset") self.shortcut_reset = QShortcut(QtGui.QKeySequence('Enter'), self) self.shortcut_reset.activated.connect(self.reset) # HORIZONTAL LAYOUT self.h_box_german = QHBoxLayout() self.h_box_german.addWidget(self.languages[0][0]) self.h_box_german.addWidget(self.languages[0][1]) self.h_box_english = QHBoxLayout() self.h_box_english.addWidget(self.languages[1][0]) self.h_box_english.addWidget(self.languages[1][1]) self.h_box_norwegian = QHBoxLayout() self.h_box_norwegian.addWidget(self.languages[2][0]) self.h_box_norwegian.addWidget(self.languages[2][1]) self.h_box_french = QHBoxLayout() self.h_box_french.addWidget(self.languages[3][0]) self.h_box_french.addWidget(self.languages[3][1]) self.h_box_random = QHBoxLayout() self.h_box_random.addWidget(self.languages[4][0]) self.h_box_random.addWidget(self.languages[4][1]) self.h_box_buttons = QHBoxLayout() self.h_box_buttons.addWidget(self.translate_button) self.h_box_buttons.addWidget(self.reset_button) # ADD LAYOUTS self.v_box.addLayout(self.h_box_german) self.v_box.addLayout(self.h_box_english) self.v_box.addLayout(self.h_box_norwegian) self.v_box.addLayout(self.h_box_french) self.v_box.addLayout(self.h_box_random) self.v_box.addLayout(self.h_box_buttons) self.setCentralWidget(self.centralwidget)
class SearchWidget(QFrame): """Widget, appeared, when Ctrl+F pressed. Has different forms for different search modes """ Normal = 'normal' Good = 'good' Bad = 'bad' Incorrect = 'incorrect' visibilityChanged = pyqtSignal(bool) """ visibilityChanged(visible) **Signal** emitted, when widget has been shown or hidden """ # pylint: disable=W0105 searchInDirectoryStartPressed = pyqtSignal(type(re.compile('')), list, str) """ searchInDirectoryStartPressed(regEx, mask, path) **Signal** emitted, when 'search in directory' button had been pressed """ # pylint: disable=W0105 searchInDirectoryStopPressed = pyqtSignal() """ searchInDirectoryStopPressed() **Signal** emitted, when 'stop search in directory' button had been pressed """ # pylint: disable=W0105 replaceCheckedStartPressed = pyqtSignal(str) """ replaceCheckedStartPressed(replText) **Signal** emitted, when 'replace checked' button had been pressed """ # pylint: disable=W0105 replaceCheckedStopPressed = pyqtSignal() """ replaceCheckedStartPressed() **Signal** emitted, when 'stop replacing checked' button had been pressed """ # pylint: disable=W0105 searchRegExpChanged = pyqtSignal(type(re.compile(''))) """ searchRegExpValidStateChanged(regEx) **Signal** emitted, when search regexp has been changed. If reg exp is invalid - regEx object contains empty pattern """ # pylint: disable=W0105 searchNext = pyqtSignal() """ searchNext() **Signal** emitted, when 'Search Next' had been pressed """ # pylint: disable=W0105 searchPrevious = pyqtSignal() """ searchPrevious() **Signal** emitted, when 'Search Previous' had been pressed """ # pylint: disable=W0105 replaceFileOne = pyqtSignal(str) """ replaceFileOne(replText) **Signal** emitted, when 'Replace' had been pressed """ # pylint: disable=W0105 replaceFileAll = pyqtSignal(str) """ replaceFileAll(replText) **Signal** emitted, when 'Replace All' had been pressed """ # pylint: disable=W0105 def __init__(self, plugin): QFrame.__init__(self, core.workspace()) self._mode = None self.plugin = plugin uic.loadUi(os.path.join(os.path.dirname(__file__), 'SearchWidget.ui'), self) self.cbSearch.setCompleter(None) self.cbReplace.setCompleter(None) self.cbMask.setCompleter(None) self.fsModel = QDirModel(self.cbPath.lineEdit()) self.fsModel.setFilter(QDir.AllDirs | QDir.NoDotAndDotDot) self.cbPath.lineEdit().setCompleter(QCompleter(self.fsModel, self.cbPath.lineEdit())) self._pathBackspaceShortcut = QShortcut(QKeySequence("Ctrl+Backspace"), self.cbPath, self._onPathBackspace) self._pathBackspaceShortcut.setContext(Qt.WidgetWithChildrenShortcut) # TODO QDirModel is deprecated but QCompleter does not yet handle # QFileSystemodel - please update when possible.""" self.cbSearch.setCompleter(None) self.pbSearchStop.setVisible(False) self.pbReplaceCheckedStop.setVisible(False) self._progress = QProgressBar(self) self._progress.setAlignment(Qt.AlignCenter) self._progress.setToolTip(self.tr("Search in progress...")) self._progress.setMaximumSize(QSize(80, 16)) core.mainWindow().statusBar().insertPermanentWidget(1, self._progress) self._progress.setVisible(False) # cd up action self.tbCdUp = QToolButton(self.cbPath.lineEdit()) self.tbCdUp.setIcon(QIcon(":/enkiicons/go-up.png")) self.tbCdUp.setCursor(Qt.ArrowCursor) self.tbCdUp.installEventFilter(self) # for drawing button self.cbSearch.installEventFilter(self) # for catching Tab and Shift+Tab self.cbReplace.installEventFilter(self) # for catching Tab and Shift+Tab self.cbPath.installEventFilter(self) # for catching Tab and Shift+Tab self.cbMask.installEventFilter(self) # for catching Tab and Shift+Tab self._closeShortcut = QShortcut(QKeySequence("Esc"), self) self._closeShortcut.setContext(Qt.WidgetWithChildrenShortcut) self._closeShortcut.activated.connect(self.hide) # connections self.cbSearch.lineEdit().textChanged.connect(self._onSearchRegExpChanged) self.cbSearch.lineEdit().returnPressed.connect(self._onReturnPressed) self.cbReplace.lineEdit().returnPressed.connect(self._onReturnPressed) self.cbPath.lineEdit().returnPressed.connect(self._onReturnPressed) self.cbMask.lineEdit().returnPressed.connect(self._onReturnPressed) self.cbRegularExpression.stateChanged.connect(self._onSearchRegExpChanged) self.cbCaseSensitive.stateChanged.connect(self._onSearchRegExpChanged) self.cbWholeWord.stateChanged.connect(self._onSearchRegExpChanged) self.tbCdUp.clicked.connect(self._onCdUpPressed) self.pbNext.pressed.connect(self.searchNext) self.pbPrevious.pressed.connect(self.searchPrevious) self.pbSearchStop.pressed.connect(self.searchInDirectoryStopPressed) self.pbReplaceCheckedStop.pressed.connect(self.replaceCheckedStopPressed) core.mainWindow().hideAllWindows.connect(self.hide) core.workspace().escPressed.connect(self.hide) core.workspace().currentDocumentChanged.connect( lambda old, new: self.setVisible(self.isVisible() and new is not None)) def show(self): """Reimplemented function. Sends signal """ super(SearchWidget, self).show() self.visibilityChanged.emit(self.isVisible()) def hide(self): """Reimplemented function. Sends signal, returns focus to workspace """ super(SearchWidget, self).hide() core.workspace().focusCurrentDocument() self.visibilityChanged.emit(self.isVisible()) def setVisible(self, visible): """Reimplemented function. Sends signal """ super(SearchWidget, self).setVisible(visible) self.visibilityChanged.emit(self.isVisible()) def _regExEscape(self, text): """Improved version of re.escape() Doesn't escape space, comma, underscore. Escapes \n and \t """ text = re.escape(text) # re.escape escapes space, comma, underscore, but, it is not necessary and makes text not readable for symbol in (' ,_=\'"/:@#%&'): text = text.replace('\\' + symbol, symbol) text = text.replace('\\\n', '\\n') text = text.replace('\\\t', '\\t') return text def _makeEscapeSeqsVisible(self, text): """Replace invisible \n and \t with escape sequences """ text = text.replace('\\', '\\\\') text = text.replace('\t', '\\t') text = text.replace('\n', '\\n') return text def setMode(self, mode): """Change search mode. i.e. from "Search file" to "Replace directory" """ if self._mode == mode and self.isVisible(): if core.workspace().currentDocument() is not None and \ not core.workspace().currentDocument().hasFocus(): self.cbSearch.lineEdit().selectAll() self.cbSearch.setFocus() self._mode = mode # Set Search and Replace text document = core.workspace().currentDocument() if document is not None and \ document.hasFocus() and \ document.qutepart.selectedText: searchText = document.qutepart.selectedText self.cbReplace.setEditText(self._makeEscapeSeqsVisible(searchText)) if self.cbRegularExpression.checkState() == Qt.Checked: searchText = self._regExEscape(searchText) self.cbSearch.setEditText(searchText) if not self.cbReplace.lineEdit().text() and \ self.cbSearch.lineEdit().text() and \ not self.cbRegularExpression.checkState() == Qt.Checked: replaceText = self.cbSearch.lineEdit().text().replace('\\', '\\\\') self.cbReplace.setEditText(replaceText) # Move focus to Search edit self.cbSearch.setFocus() self.cbSearch.lineEdit().selectAll() # Set search path if mode & MODE_FLAG_DIRECTORY and \ not (self.isVisible() and self.cbPath.isVisible()): try: searchPath = os.path.abspath(str(os.path.curdir)) except OSError: # current directory might have been deleted pass else: self.cbPath.setEditText(searchPath) # Set widgets visibility flag according to state widgets = (self.wSearch, self.pbPrevious, self.pbNext, self.pbSearch, self.wReplace, self.wPath, self.pbReplace, self.pbReplaceAll, self.pbReplaceChecked, self.wOptions, self.wMask) # wSear pbPrev pbNext pbSear wRepl wPath pbRep pbRAll pbRCHK wOpti wMask visible = \ {MODE_SEARCH: (1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 0,), MODE_REPLACE: (1, 1, 1, 0, 1, 0, 1, 1, 0, 1, 0,), MODE_SEARCH_DIRECTORY: (1, 0, 0, 1, 0, 1, 0, 0, 0, 1, 1,), MODE_REPLACE_DIRECTORY: (1, 0, 0, 1, 1, 1, 0, 0, 1, 1, 1,), MODE_SEARCH_OPENED_FILES: (1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1,), MODE_REPLACE_OPENED_FILES: (1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1,)} for i, widget in enumerate(widgets): widget.setVisible(visible[mode][i]) # Search next button text if mode == MODE_REPLACE: self.pbNext.setText('Next') else: self.pbNext.setText('Next↵') # Finaly show all with valid size self.show() # show before updating widgets and labels self._updateLabels() self._updateWidgets() def eventFilter(self, object_, event): """ Event filter for mode switch tool button Draws icons in the search and path lineEdits """ if event.type() == QEvent.Paint and object_ is self.tbCdUp: # draw CdUp button in search path QLineEdit toolButton = object_ lineEdit = self.cbPath.lineEdit() lineEdit.setContentsMargins(lineEdit.height(), 0, 0, 0) height = lineEdit.height() availableRect = QRect(0, 0, height, height) if toolButton.rect() != availableRect: toolButton.setGeometry(availableRect) painter = QPainter(toolButton) toolButton.icon().paint(painter, availableRect) return True elif event.type() == QEvent.KeyPress: # Tab and Shift+Tab in QLineEdits if event.key() == Qt.Key_Tab: self._moveFocus(1) return True elif event.key() == Qt.Key_Backtab: self._moveFocus(-1) return True return QFrame.eventFilter(self, object_, event) def _onReturnPressed(self): """Return or Enter pressed on widget. Search next or Replace next """ if self.pbReplace.isVisible(): self.pbReplace.click() elif self.pbNext.isVisible(): self.pbNext.click() elif self.pbSearch.isVisible(): self.pbSearch.click() elif self.pbSearchStop.isVisible(): self.pbSearchStop.click() def _onPathBackspace(self): """Ctrl+Backspace pressed on path. Remove 1 path level. Default behavior would be to remove one word on Linux or all on Windows """ path = self.cbPath.currentText() if path.endswith('/') or \ path.endswith('\\'): path = path[:-1] head, tail = os.path.split(path) if head and \ head != path: if not head.endswith(os.sep): head += os.sep self.cbPath.lineEdit().setText(head) def _moveFocus(self, step): """Move focus forward or backward according to step. Standard Qt Keyboard focus algorithm doesn't allow circular navigation """ allFocusableWidgets = (self.cbSearch, self.cbReplace, self.cbPath, self.cbMask) visibleWidgets = [widget for widget in allFocusableWidgets if widget.isVisible()] try: focusedIndex = visibleWidgets.index(QApplication.focusWidget()) except ValueError: print('Invalid focused widget in Search Widget', file=sys.stderr) return nextFocusedIndex = (focusedIndex + step) % len(visibleWidgets) visibleWidgets[nextFocusedIndex].setFocus() visibleWidgets[nextFocusedIndex].lineEdit().selectAll() def _updateLabels(self): """Update 'Search' 'Replace' 'Path' labels geometry """ width = 0 if self.lSearch.isVisible(): width = max(width, self.lSearch.minimumSizeHint().width()) if self.lReplace.isVisible(): width = max(width, self.lReplace.minimumSizeHint().width()) if self.lPath.isVisible(): width = max(width, self.lPath.minimumSizeHint().width()) self.lSearch.setMinimumWidth(width) self.lReplace.setMinimumWidth(width) self.lPath.setMinimumWidth(width) def _updateWidgets(self): """Update geometry of widgets with buttons """ width = 0 if self.wSearchRight.isVisible(): width = max(width, self.wSearchRight.minimumSizeHint().width()) if self.wReplaceRight.isVisible(): width = max(width, self.wReplaceRight.minimumSizeHint().width()) if self.wPathRight.isVisible(): width = max(width, self.wPathRight.minimumSizeHint().width()) self.wSearchRight.setMinimumWidth(width) self.wReplaceRight.setMinimumWidth(width) self.wPathRight.setMinimumWidth(width) def updateComboBoxes(self): """Update comboboxes with last used texts """ searchText = self.cbSearch.currentText() replaceText = self.cbReplace.currentText() maskText = self.cbMask.currentText() # search if searchText: index = self.cbSearch.findText(searchText) if index == -1: self.cbSearch.addItem(searchText) # replace if replaceText: index = self.cbReplace.findText(replaceText) if index == -1: self.cbReplace.addItem(replaceText) # mask if maskText: index = self.cbMask.findText(maskText) if index == -1: self.cbMask.addItem(maskText) def _searchPatternTextAndFlags(self): """Get search pattern and flags """ pattern = self.cbSearch.currentText() pattern = pattern.replace('\u2029', '\n') # replace unicode paragraph separator with habitual \n if not self.cbRegularExpression.checkState() == Qt.Checked: pattern = re.escape(pattern) if self.cbWholeWord.checkState() == Qt.Checked: pattern = r'\b' + pattern + r'\b' flags = 0 if not self.cbCaseSensitive.checkState() == Qt.Checked: flags = re.IGNORECASE return pattern, flags def getRegExp(self): """Read search parameters from controls and present it as a regular expression """ pattern, flags = self._searchPatternTextAndFlags() return re.compile(pattern, flags) def isSearchRegExpValid(self): """Try to compile search pattern to check if it is valid Returns bool result and text error """ pattern, flags = self._searchPatternTextAndFlags() try: re.compile(pattern, flags) except re.error as ex: return False, str(ex) return True, None def _getSearchMask(self): """Get search mask as list of patterns """ mask = [s.strip() for s in self.cbMask.currentText().split(' ')] # remove empty mask = [_f for _f in mask if _f] return mask def setState(self, state): """Change line edit color according to search result """ widget = self.cbSearch.lineEdit() color = {SearchWidget.Normal: QApplication.instance().palette().color(QPalette.Base), SearchWidget.Good: QColor(Qt.green), SearchWidget.Bad: QColor(Qt.red), SearchWidget.Incorrect: QColor(Qt.darkYellow)} stateColor = color[state] if state != SearchWidget.Normal: stateColor.setAlpha(100) pal = widget.palette() pal.setColor(widget.backgroundRole(), stateColor) widget.setPalette(pal) def setSearchInProgress(self, inProgress): """Search thread started or stopped """ self.pbSearchStop.setVisible(inProgress) self.pbSearch.setVisible(not inProgress) self._updateWidgets() self._progress.setVisible(inProgress) def onSearchProgressChanged(self, value, total): """Signal from the thread, progress changed """ self._progress.setValue(value) self._progress.setMaximum(total) def setReplaceInProgress(self, inProgress): """Replace thread started or stopped """ self.pbReplaceCheckedStop.setVisible(inProgress) self.pbReplaceChecked.setVisible(not inProgress) self._updateWidgets() def setSearchInFileActionsEnabled(self, enabled): """Set enabled state for Next, Prev, Replace, ReplaceAll """ for button in (self.pbNext, self.pbPrevious, self.pbReplace, self.pbReplaceAll): button.setEnabled(enabled) def _onSearchRegExpChanged(self): """User edited search text or checked/unchecked checkboxes """ valid, error = self.isSearchRegExpValid() if valid: self.setState(self.Normal) core.mainWindow().statusBar().clearMessage() self.pbSearch.setEnabled(len(self.getRegExp().pattern) > 0) else: core.mainWindow().statusBar().showMessage(error, 3000) self.setState(self.Incorrect) self.pbSearch.setEnabled(False) self.searchRegExpChanged.emit(re.compile('')) return self.searchRegExpChanged.emit(self.getRegExp()) def _onCdUpPressed(self): """User pressed "Up" button, need to remove one level from search path """ text = self.cbPath.currentText() if not os.path.exists(text): return editText = os.path.normpath(os.path.join(text, os.path.pardir)) self.cbPath.setEditText(editText) def on_pbSearch_pressed(self): """Handler of click on "Search" button (for search in directory) """ self.setState(SearchWidget.Normal) self.searchInDirectoryStartPressed.emit(self.getRegExp(), self._getSearchMask(), self.cbPath.currentText()) def on_pbReplace_pressed(self): """Handler of click on "Replace" (in file) button """ self.replaceFileOne.emit(self.cbReplace.currentText()) def on_pbReplaceAll_pressed(self): """Handler of click on "Replace all" (in file) button """ self.replaceFileAll.emit(self.cbReplace.currentText()) def on_pbReplaceChecked_pressed(self): """Handler of click on "Replace checked" (in directory) button """ self.replaceCheckedStartPressed.emit(self.cbReplace.currentText()) def on_pbBrowse_pressed(self): """Handler of click on "Browse" button. Explores FS for search directory path """ path = QFileDialog.getExistingDirectory(self, self.tr("Search path"), self.cbPath.currentText()) if path: self.cbPath.setEditText(path)
def __init__(self, theParent): QDialog.__init__(self, theParent) logger.debug("Initialising GuiProjectLoad ...") self.setObjectName("GuiProjectLoad") self.mainConf = nw.CONFIG self.theParent = theParent self.theTheme = theParent.theTheme self.openState = self.NONE_STATE self.openPath = None sPx = self.mainConf.pxInt(16) nPx = self.mainConf.pxInt(96) iPx = self.theTheme.baseIconSize self.outerBox = QVBoxLayout() self.innerBox = QHBoxLayout() self.outerBox.setSpacing(sPx) self.innerBox.setSpacing(sPx) self.setWindowTitle(self.tr("Open Project")) self.setMinimumWidth(self.mainConf.pxInt(650)) self.setMinimumHeight(self.mainConf.pxInt(400)) self.setModal(True) self.nwIcon = QLabel() self.nwIcon.setPixmap(self.theParent.theTheme.getPixmap("novelwriter", (nPx, nPx))) self.innerBox.addWidget(self.nwIcon, 0, Qt.AlignTop) self.projectForm = QGridLayout() self.projectForm.setContentsMargins(0, 0, 0, 0) self.listBox = QTreeWidget() self.listBox.setSelectionMode(QAbstractItemView.SingleSelection) self.listBox.setDragDropMode(QAbstractItemView.NoDragDrop) self.listBox.setColumnCount(3) self.listBox.setHeaderLabels([ self.tr("Working Title"), self.tr("Words"), self.tr("Last Opened"), ]) self.listBox.setRootIsDecorated(False) self.listBox.itemSelectionChanged.connect(self._doSelectRecent) self.listBox.itemDoubleClicked.connect(self._doOpenRecent) self.listBox.setIconSize(QSize(iPx, iPx)) treeHead = self.listBox.headerItem() treeHead.setTextAlignment(self.C_COUNT, Qt.AlignRight) treeHead.setTextAlignment(self.C_TIME, Qt.AlignRight) self.lblRecent = QLabel("<b>%s</b>" % self.tr("Recently Opened Projects")) self.lblPath = QLabel("<b>%s</b>" % self.tr("Path")) self.selPath = QLineEdit("") self.selPath.setReadOnly(True) self.browseButton = QPushButton("...") self.browseButton.setMaximumWidth(int(2.5*self.theTheme.getTextWidth("..."))) self.browseButton.clicked.connect(self._doBrowse) self.projectForm.addWidget(self.lblRecent, 0, 0, 1, 3) self.projectForm.addWidget(self.listBox, 1, 0, 1, 3) self.projectForm.addWidget(self.lblPath, 2, 0, 1, 1) self.projectForm.addWidget(self.selPath, 2, 1, 1, 1) self.projectForm.addWidget(self.browseButton, 2, 2, 1, 1) self.projectForm.setColumnStretch(0, 0) self.projectForm.setColumnStretch(1, 1) self.projectForm.setColumnStretch(2, 0) self.projectForm.setVerticalSpacing(self.mainConf.pxInt(4)) self.projectForm.setHorizontalSpacing(self.mainConf.pxInt(8)) self.innerBox.addLayout(self.projectForm) self.buttonBox = QDialogButtonBox(QDialogButtonBox.Open | QDialogButtonBox.Cancel) self.buttonBox.accepted.connect(self._doOpenRecent) self.buttonBox.rejected.connect(self._doCancel) self.newButton = self.buttonBox.addButton(self.tr("New"), QDialogButtonBox.ActionRole) self.newButton.clicked.connect(self._doNewProject) self.delButton = self.buttonBox.addButton(self.tr("Remove"), QDialogButtonBox.ActionRole) self.delButton.clicked.connect(self._doDeleteRecent) self.outerBox.addLayout(self.innerBox) self.outerBox.addWidget(self.buttonBox) self.setLayout(self.outerBox) self._populateList() self._doSelectRecent() keyDelete = QShortcut(self.listBox) keyDelete.setKey(QKeySequence(Qt.Key_Delete)) keyDelete.activated.connect(self._doDeleteRecent) logger.debug("GuiProjectLoad initialisation complete") return
class Lookup(QWidget): MODEL_CLASS = None def __init__(self, parent, model): QWidget.__init__(self, parent, Qt.Window) self.model = model self.model.view = self self._setupUi() self.searchEdit.searchChanged.connect(self.searchChanged) self.searchEdit.returnPressed.connect(self.returnPressed) self.namesList.currentRowChanged.connect(self.currentRowChanged) self.namesList.itemDoubleClicked.connect(self.itemDoubleClicked) self._shortcutUp.activated.connect(self.upPressed) self._shortcutDown.activated.connect(self.downPressed) def _setupUi(self): self.setWindowTitle(tr("Lookup")) self.resize(314, 331) self.verticalLayout = QVBoxLayout(self) self.searchEdit = SearchEdit(self) self.verticalLayout.addWidget(self.searchEdit) self.namesList = QListWidget(self) self.namesList.setEditTriggers(QAbstractItemView.NoEditTriggers) self.namesList.setSelectionBehavior(QAbstractItemView.SelectRows) self.namesList.setUniformItemSizes(True) self.namesList.setSelectionRectVisible(True) self.verticalLayout.addWidget(self.namesList) self.searchEdit.immediate = True self._shortcutUp = QShortcut(self.searchEdit) self._shortcutUp.setKey(QKeySequence(Qt.Key_Up)) self._shortcutUp.setContext(Qt.WidgetShortcut) self._shortcutDown = QShortcut(self.searchEdit) self._shortcutDown.setKey(QKeySequence(Qt.Key_Down)) self._shortcutDown.setContext(Qt.WidgetShortcut) def _restoreSelection(self): self.namesList.setCurrentRow(self.model.selected_index) #--- Event Handlers def returnPressed(self): self.model.go() def searchChanged(self): self.model.search_query = str(self.searchEdit.text()) def currentRowChanged(self, row): if row >= 0: self.model.selected_index = row def itemDoubleClicked(self, item): self.model.go() def upPressed(self): if self.namesList.currentRow() > 0: self.namesList.setCurrentRow(self.namesList.currentRow()-1) def downPressed(self): if self.namesList.currentRow() < self.namesList.count()-1: self.namesList.setCurrentRow(self.namesList.currentRow()+1) #--- model --> view def refresh(self): self.namesList.clear() self.namesList.addItems(self.model.names) self._restoreSelection() self.searchEdit.setText(self.model.search_query) def show(self): QWidget.show(self) self.searchEdit.setFocus() # see csv_options self.raise_() def hide(self): QWidget.hide(self)
def setupUi(self, MainWindow): MainWindow.setObjectName("MainWindow") MainWindow.resize(760, 503) QShortcut(QtGui.QKeySequence("Backspace"), MainWindow, self.onClickBack) QShortcut(QtGui.QKeySequence("Return"), MainWindow, self.onClickGoTo) QShortcut(QtGui.QKeySequence("CTRL+c"), MainWindow, self.copyEvent) QShortcut(QtGui.QKeySequence("CTRL+v"), MainWindow, self.pasteEvent) QShortcut(QtGui.QKeySequence("CTRL+x"), MainWindow, self.cutEvent) QShortcut(QtGui.QKeySequence("CTRL+n"), MainWindow, self.newFolderEvent) QShortcut(QtGui.QKeySequence("CTRL+Backspace"), MainWindow, self.deleteEvent) self.current_path = '/' self.file_list=[] self.history = [main.current_path] self.mainServerConnectionSocket = socket.socket() self.connectedDevices ={} self.selected_items = [] self.cut_selected_items = [] self.favorite_list = [] self.centralwidget = QtWidgets.QWidget(MainWindow) self.centralwidget.setObjectName("centralwidget") self.verticalLayoutWidget = QtWidgets.QWidget(self.centralwidget) self.verticalLayoutWidget.setGeometry(QtCore.QRect(170, 50, 591, 381)) self.verticalLayoutWidget.setObjectName("verticalLayoutWidget") self.verticalLayout = QtWidgets.QVBoxLayout(self.verticalLayoutWidget) self.verticalLayout.setContentsMargins(0, 0, 0, 0) self.verticalLayout.setObjectName("verticalLayout") self.itemsView = QtWidgets.QTableWidget(self.verticalLayoutWidget) self.itemsView.setObjectName("itemsView") self.itemsView.setEditTriggers(QAbstractItemView.NoEditTriggers) self.itemsView.doubleClicked.connect(self.tableClicked) self.verticalLayout.addWidget(self.itemsView) self.favoriteView = QtWidgets.QTableWidget(self.centralwidget) self.favoriteView.setGeometry(QtCore.QRect(0, 70, 161, 341)) self.favoriteView.setEditTriggers(QAbstractItemView.NoEditTriggers) self.favoriteView.setVerticalHeaderLabels(()) self.favoriteView.doubleClicked.connect(self.favoriteTableClicked) self.favoriteView.setObjectName("FavoriteView") self.directoryTextView = QtWidgets.QTextEdit(self.centralwidget) self.directoryTextView.insertPlainText('hamidreza') self.directoryTextView.setGeometry(QtCore.QRect(170, 10, 401, 31)) self.directoryTextView.setObjectName("directoryTextView") self.serverButton=QtWidgets.QPushButton(self.centralwidget) self.serverButton.setIcon(QtGui.QIcon(QtGui.QPixmap("server.png"))) self.serverButton.setIconSize(QtCore.QSize(37,37)) self.serverButton.clicked.connect(self.makeServer) self.serverButton.setGeometry(QtCore.QRect(630, 0, 60, 50)) self.clientButton = QtWidgets.QPushButton(self.centralwidget) self.clientButton.setIcon(QtGui.QIcon(QtGui.QPixmap("client.png"))) self.clientButton.setIconSize(QtCore.QSize(37, 37)) self.clientButton.clicked.connect(self.connectTo) self.clientButton.setGeometry(QtCore.QRect(690, 0, 60, 50)) self.pushButton = QtWidgets.QPushButton(self.centralwidget) self.pushButton.clicked.connect(self.onClickGoTo) self.pushButton.setGeometry(QtCore.QRect(570, 20, 60, 28)) self.pushButton_2 = QtWidgets.QPushButton('back',self.centralwidget) self.pushButton_2.setGeometry(QtCore.QRect(570, 0, 60, 28)) self.pushButton_2.clicked.connect(self.onClickBack) self.newFolderButton = QtWidgets.QPushButton(self.centralwidget) self.newFolderButton.setGeometry(QtCore.QRect(170, 430, 91, 32)) self.newFolderButton.setObjectName("newFolderButton") self.newFolderButton.setText("New Folder") self.newFolderButton.clicked.connect(self.newFolderEvent) self.copyButton = QtWidgets.QPushButton(self.centralwidget) self.copyButton.setGeometry(QtCore.QRect(271-5, 430, 91, 32)) self.copyButton.setObjectName("copyButton") self.copyButton.setText("Copy") self.copyButton.clicked.connect(self.copyEvent) self.cutButton = QtWidgets.QPushButton(self.centralwidget) self.cutButton.setGeometry(QtCore.QRect(372-10, 430, 91, 32)) self.cutButton.setObjectName("cutButton") self.cutButton.setText("Cut") self.cutButton.clicked.connect(self.cutEvent) self.pasteButton = QtWidgets.QPushButton(self.centralwidget) self.pasteButton.setGeometry(QtCore.QRect(473-15, 430, 91, 32)) self.pasteButton.setObjectName("pasteButton") self.pasteButton.setText("Paste") self.pasteButton.clicked.connect(self.pasteEvent) self.shareComboBox = QtWidgets.QComboBox(self.centralwidget) self.shareComboBox.setGeometry(QtCore.QRect(473 + 101 , 430, 100, 32)) self.shareComboBox.setObjectName("shareComboBox") icon = QtGui.QIcon(QtGui.QPixmap("pc.png")) self.shareComboBox.addItem("pc1") self.shareComboBox.addItem("pc2") self.shareComboBox.setItemIcon(0, icon) self.shareComboBox.setItemIcon(1,icon) self.selectComboBox = QtWidgets.QComboBox(self.centralwidget) self.selectComboBox.setGeometry(QtCore.QRect(10, 10, 150, 32)) self.selectComboBox.setObjectName("selectComboBox") self.selectComboBox.addItem("pc1") self.selectComboBox.addItem("pc2") self.selectComboBox.setItemIcon(0, icon) self.selectComboBox.setItemIcon(1, icon) self.selectComboBox.activated.connect(self.sourceChanged) self.shareButton = QtWidgets.QPushButton(self.centralwidget) self.shareButton.setGeometry(QtCore.QRect(675, 430, 60, 32)) self.shareButton.setObjectName("shareButton") self.shareButton.setText("Share") self.shareButton.clicked.connect(self.shareEvent) self.favoriteLabel = QtWidgets.QLabel(self.centralwidget) self.favoriteLabel.setGeometry(QtCore.QRect(55, 50, 81, 16)) self.favoriteLabel.setObjectName("favoriteLabel") self.favoriteLabel.setText("Favorites") self.addButton = QtWidgets.QToolButton(self.centralwidget) self.addButton.setGeometry(QtCore.QRect(0, 410, 161, 21)) self.addButton.setObjectName("addButton") self.addButton.setText("Add to favorites") self.addButton.clicked.connect(self.addEvent) self.removeFavoriteButton = QtWidgets.QToolButton(self.centralwidget) self.removeFavoriteButton.setGeometry(QtCore.QRect(0, 430, 161, 21)) self.removeFavoriteButton.setObjectName("removeFavoriteButton") self.removeFavoriteButton.setText("Remove from favorites") self.removeFavoriteButton.clicked.connect(self.removeFavoriteEvent) #self.pushButton_2.setObjectName("pushButton_2") MainWindow.setCentralWidget(self.centralwidget) self.menubar = QtWidgets.QMenuBar(MainWindow) self.menubar.setGeometry(QtCore.QRect(0, 0, 800, 21)) self.menubar.setObjectName("menubar") self.menuFile = QtWidgets.QMenu(self.menubar) self.menuFile.setObjectName("menuFile") self.menuEdit = QtWidgets.QMenu(self.menubar) self.menuEdit.setObjectName("menuEdit") self.menuView = QtWidgets.QMenu(self.menubar) self.menuView.setObjectName("menuView") self.menuChange_View = QtWidgets.QMenu(self.menuView) self.menuChange_View.setObjectName("menuChange_View") MainWindow.setMenuBar(self.menubar) self.statusbar = QtWidgets.QStatusBar(MainWindow) self.statusbar.setObjectName("statusbar") MainWindow.setStatusBar(self.statusbar) self.actionOpen = QtWidgets.QAction(MainWindow) self.actionOpen.setObjectName("actionOpen") self.actionUndo = QtWidgets.QAction(MainWindow) self.actionUndo.setObjectName("actionUndo") self.actionDelete = QtWidgets.QAction(MainWindow) self.actionDelete.setObjectName("actionDelete") self.actionPreview = QtWidgets.QAction(MainWindow) self.actionPreview.setObjectName("actionPreview") self.actionExit = QtWidgets.QAction(MainWindow) self.actionExit.setObjectName("actionExit") self.actionCopy = QtWidgets.QAction(MainWindow) self.actionCopy.setObjectName("actionCopy") self.actionCut = QtWidgets.QAction(MainWindow) self.actionCut.setObjectName("actionCut") self.actionPaste = QtWidgets.QAction(MainWindow) self.actionPaste.setObjectName("actionPaste") self.actionSelect_All = QtWidgets.QAction(MainWindow) self.actionSelect_All.setObjectName("actionSelect_All") self.actionProperties = QtWidgets.QAction(MainWindow) self.actionProperties.setObjectName("actionProperties") self.actionLayouts = QtWidgets.QAction(MainWindow) self.actionLayouts.setObjectName("actionLayouts") self.actionLarge = QtWidgets.QAction(MainWindow) self.actionLarge.setObjectName("actionLarge") self.actionMedium = QtWidgets.QAction(MainWindow) self.actionMedium.setObjectName("actionMedium") self.actionSmall = QtWidgets.QAction(MainWindow) self.actionSmall.setObjectName("actionSmall") self.actionSort = QtWidgets.QAction(MainWindow) self.actionSort.setObjectName("actionSort") self.menuFile.addAction(self.actionExit) self.menuEdit.addAction(self.actionSort) self.menuEdit.addAction(self.actionCopy) self.menuEdit.addAction(self.actionCut) self.menuEdit.addAction(self.actionPaste) self.menuEdit.addAction(self.actionSelect_All) self.menuChange_View.addAction(self.actionLarge) self.menuChange_View.addAction(self.actionMedium) self.menuChange_View.addAction(self.actionSmall) self.menuView.addAction(self.menuChange_View.menuAction()) self.menubar.addAction(self.menuFile.menuAction()) self.menubar.addAction(self.menuEdit.menuAction()) self.menubar.addAction(self.menuView.menuAction()) self.actionSort.triggered.connect(self.sortRefresh) self.actionExit.triggered.connect(self.exitApp) self.retranslateUi(MainWindow) QtCore.QMetaObject.connectSlotsByName(MainWindow)
def create_app(self): self.layout = QVBoxLayout() self.toolbar = QWidget() self.toolbar.setObjectName("toolbar") self.toolbar_layout = QHBoxLayout() self.layout.setSpacing(0) self.layout.setContentsMargins(0, 0, 0, 0) self.shortcutNewTab = QShortcut(QKeySequence("Ctrl+T"), self) self.shortcutNewTab.activated.connect(self.add_tab) self.shortcutReload = QShortcut(QKeySequence("Ctrl+R"), self) self.shortcutReload.activated.connect(self.reload_page) # Create Tabs self.tab_bar = QTabBar(movable=True, tabsClosable=True) self.tab_bar.tabCloseRequested.connect(self.close_tab) self.tab_bar.tabBarClicked.connect(self.switch_tab) self.tab_bar.setCurrentIndex(0) self.tab_bar.setDrawBase(False) # Keep track of tabs self.tab_count = 0 self.tabs = [] # Add Tab Button self.AddTabButton = QPushButton("+") self.AddTabButton.clicked.connect(self.add_tab) # Create address bar self.address_bar = Address_Bar() self.address_bar.returnPressed.connect(self.browse_to) # Set Toolbar Buttons self.back_button = QPushButton("<") self.back_button.clicked.connect(self.go_back) self.forward_button = QPushButton(">") self.forward_button.clicked.connect(self.go_forward) self.reload_button = QPushButton("R") self.reload_button.clicked.connect(self.reload_page) #Build Toolbar self.toolbar.setLayout(self.toolbar_layout) self.toolbar_layout.addWidget(self.back_button) self.toolbar_layout.addWidget(self.forward_button) self.toolbar_layout.addWidget(self.reload_button) self.toolbar_layout.addWidget(self.address_bar) self.toolbar_layout.addWidget(self.AddTabButton) # Set Main View self.container = QWidget() self.container.layout = QStackedLayout() self.container.setLayout(self.container.layout) self.layout.addWidget(self.tab_bar) self.layout.addWidget(self.toolbar) self.layout.addWidget(self.container) self.setLayout(self.layout) self.add_tab() self.show()
def __init__(self, parent=None): super().__init__() self.setupUi(self) self.setWindowTitle('Vorta for Borg Backup') self.app = parent self.setWindowIcon(get_colored_icon("icon")) self.setWindowFlags(QtCore.Qt.WindowCloseButtonHint | QtCore.Qt.WindowMinimizeButtonHint) self.createStartBtn = LoadingButton(self.tr("Start Backup")) self.gridLayout.addWidget(self.createStartBtn, 0, 0, 1, 1) self.createStartBtn.setGif(get_asset("icons/loading")) # Use previous window state previous_window_width = SettingsModel.get(key='previous_window_width') previous_window_height = SettingsModel.get( key='previous_window_height') self.resize(int(previous_window_width.str_value), int(previous_window_height.str_value)) # Select previously used profile, if available prev_profile_id = SettingsModel.get(key='previous_profile_id') self.current_profile = BackupProfileModel.get_or_none( id=prev_profile_id.str_value) if self.current_profile is None: self.current_profile = BackupProfileModel.select().order_by( 'name').first() # Load tab models self.repoTab = RepoTab(self.repoTabSlot) self.sourceTab = SourceTab(self.sourceTabSlot) self.archiveTab = ArchiveTab(self.archiveTabSlot, app=self.app) self.scheduleTab = ScheduleTab(self.scheduleTabSlot) self.miscTab = MiscTab(self.miscTabSlot) self.miscTab.set_borg_details(borg_compat.version, borg_compat.path) self.tabWidget.setCurrentIndex(0) self.repoTab.repo_changed.connect( self.archiveTab.populate_from_profile) self.repoTab.repo_changed.connect( self.scheduleTab.populate_from_profile) self.repoTab.repo_added.connect(self.archiveTab.list_action) self.createStartBtn.clicked.connect(self.app.create_backup_action) self.cancelButton.clicked.connect(self.app.backup_cancelled_event.emit) QShortcut(QKeySequence("Ctrl+W"), self).activated.connect(self.on_close_window) QShortcut(QKeySequence("Ctrl+Q"), self).activated.connect(self.on_close_window) self.app.backup_started_event.connect(self.backup_started_event) self.app.backup_finished_event.connect(self.backup_finished_event) self.app.backup_log_event.connect(self.set_log) self.app.backup_progress_event.connect(self.set_progress) self.app.backup_cancelled_event.connect(self.backup_cancelled_event) # Init profile list self.populate_profile_selector() self.profileSelector.currentIndexChanged.connect( self.profile_select_action) self.profileRenameButton.clicked.connect(self.profile_rename_action) self.profileExportButton.clicked.connect(self.profile_export_action) self.profileDeleteButton.clicked.connect(self.profile_delete_action) profile_add_menu = QMenu() profile_add_menu.addAction(self.tr('Import from file...'), self.profile_import_action) self.profileAddButton.setMenu(profile_add_menu) self.profileAddButton.clicked.connect(self.profile_add_action) # OS-specific startup options: if not get_network_status_monitor().is_network_status_available(): # Hide Wifi-rule section in schedule tab. self.scheduleTab.wifiListLabel.hide() self.scheduleTab.wifiListWidget.hide() self.scheduleTab.page_2.hide() self.scheduleTab.toolBox.removeItem(1) # Connect to existing thread. if self.app.jobs_manager.is_worker_running(): self.createStartBtn.setEnabled(False) self.createStartBtn.start() self.cancelButton.setEnabled(True) self.set_icons()
def __setupKeyShortcuts(self, widget): widgetName=widget.objectName(); self.__keyShortcuts[widgetName]=[]; self.__keyShortcuts[widgetName].append(QShortcut(QKeySequence(self.tr("V")), widget, self.plotPoints)); self.__keyShortcuts[widgetName].append(QShortcut(QKeySequence(self.tr("C")), widget, self.plotLargePoints)); self.__keyShortcuts[widgetName].append(QShortcut(QKeySequence(self.tr("Shift+D")), widget, self.deleteCluster)); self.__keyShortcuts[widgetName].append(QShortcut(QKeySequence(self.tr("F")), widget, self.refineCluster)); self.__keyShortcuts[widgetName].append(QShortcut(QKeySequence(self.tr("A")), widget, self.addCluster)); self.__keyShortcuts[widgetName].append(QShortcut(QKeySequence(self.tr("S")), widget, self.copyCluster)); self.__keyShortcuts[widgetName].append(QShortcut(QKeySequence(self.tr("Shift+G")), widget, self.undoCluster)); self.__keyShortcuts[widgetName].append(QShortcut(QKeySequence(self.tr("Z")), widget, self.stepBackBoundary)); self.__keyShortcuts[widgetName].append(QShortcut(QKeySequence(self.tr("X")), widget, self.toggleReport)); self.__keyShortcuts[widgetName].append(QShortcut(QKeySequence(self.tr("Q")), widget, self.drawPrevWaves)); self.__keyShortcuts[widgetName].append(QShortcut(QKeySequence(self.tr("W")), widget, self.drawNextWaves)); self.__keyShortcuts[widgetName].append(QShortcut(QKeySequence(self.tr("E")), widget, self.clearWavePlots)); self.__keyShortcuts[widgetName].append(QShortcut(QKeySequence(self.tr("R")), widget, self.resetWaveInd)); self.__keyShortcuts[widgetName].append(QShortcut(QKeySequence(self.tr("T")), widget, self.toggleRefWaveChs));
def setupUi(self): super().setupUi(self.parent_widget) self.table_header = LoggerTableHeader( self.loggerTable.horizontalHeader()) self.record_model = LogRecordModel(self, self.level_filter.levels, self.table_header) self.createLevelButton.clicked.connect(self.create_level) self.loggerTable.setMouseTracking(False) self.loggerTable.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.loggerTable.verticalScrollBar().rangeChanged.connect( self.onRangeChanged) self.loggerTable.verticalScrollBar().valueChanged.connect( self.onScroll) self.loggerTable.setContextMenuPolicy(Qt.CustomContextMenu) self.loggerTable.customContextMenuRequested.connect( self.open_logger_table_menu) self.loggerTable.setStyleSheet("QTableView { border: 0px;}") self.loggerTable.verticalHeader().setDefaultSectionSize( CONFIG['logger_row_height']) self.namespaceTreeView.setModel(self.namespace_tree_model) self.namespaceTreeView.selectionModel().selectionChanged.connect( self.reset_master) self.namespaceTreeView.setContextMenuPolicy(Qt.CustomContextMenu) self.namespaceTreeView.customContextMenuRequested.connect( self.open_namespace_table_menu) self.namespace_tree_model.rowsInserted.connect( self.on_tree_rows_inserted) for levelno, level in self.level_filter.levels.items(): self.add_level_to_table(level) self.levelsTable.doubleClicked.connect(self.level_double_clicked) self.levelsTable.installEventFilter(self) self.levelsTable.setContextMenuPolicy(Qt.CustomContextMenu) self.levelsTable.customContextMenuRequested.connect( self.open_levels_table_menu) if self.filter_model_enabled: self.filter_model = RecordFilter(self, self.namespaceTreeView, self.level_filter) self.filter_model.setSourceModel(self.record_model) self.loggerTable.setModel(self.filter_model) else: self.loggerTable.setModel(self.record_model) self.loggerTable.selectionModel().selectionChanged.connect( self.update_detail) self.detailTable.setModel(self.detail_model) self.table_header_view = header = self.loggerTable.horizontalHeader() header.setStretchLastSection(True) # header.sectionResized.connect(self.table_header.column_resized) header.viewport().installEventFilter( self.table_header) # read the docstring header.setContextMenuPolicy(Qt.CustomContextMenu) header.customContextMenuRequested.connect(self.open_header_menu) self.searchSC = QShortcut('Ctrl+F', self.parent_widget) self.searchSC.activated.connect(self.toggle_search) self.searchSC.setAutoRepeat(False) self.searchSC_F3 = QShortcut('F3', self.parent_widget) self.searchSC_F3.activated.connect(self.search_down_or_close) self.searchSC_F3.setAutoRepeat(True) self.searchSC_Esc = QShortcut('Esc', self.parent_widget) self.searchSC_Esc.activated.connect( partial(self.set_search_visible, False)) self.searchSC_Esc.setAutoRepeat(False) self.searchLine.returnPressed.connect(self.search_down) self.searchDownButton.clicked.connect(self.search_down) self.searchDownButton.setMenu(self.setup_search_button_menu()) self.searchWidget.setVisible(self.search_bar_visible) self.filterButton.clicked.connect(self.filter_or_clear) self.filterButton.setToolTip( 'Adheres to the same settings as the search') # @NextVersion: make this happen self.levelButtonsLayout.setParent(None) self.createLevelButton.setVisible(False) self.presetsButton.setVisible(False) self.setup_internal_connections() self.set_columns_sizes()
def __init__(self, aPath, parent=None): super(VideoPlayer, self).__init__(parent) self.setAttribute(Qt.WA_NoSystemBackground, True) self.setAcceptDrops(True) self.mediaPlayer = QMediaPlayer(None, QMediaPlayer.StreamPlayback) self.mediaPlayer.setVolume(80) self.videoWidget = QVideoWidget(self) self.videoWidget.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) self.videoWidget.setMinimumSize(QSize(640, 360)) self.lbl = QLineEdit('00:00:00') self.lbl.setReadOnly(True) self.lbl.setFixedWidth(70) self.lbl.setUpdatesEnabled(True) self.lbl.setStyleSheet(stylesheet(self)) self.elbl = QLineEdit('00:00:00') self.elbl.setReadOnly(True) self.elbl.setFixedWidth(70) self.elbl.setUpdatesEnabled(True) self.elbl.setStyleSheet(stylesheet(self)) self.playButton = QPushButton() self.playButton.setEnabled(False) self.playButton.setFixedWidth(32) self.playButton.setStyleSheet("background-color: black") self.playButton.setIcon(self.style().standardIcon(QStyle.SP_MediaPlay)) self.playButton.clicked.connect(self.play) self.positionSlider = QSlider(Qt.Horizontal, self) self.positionSlider.setStyleSheet(stylesheet(self)) self.positionSlider.setRange(0, 100) self.positionSlider.sliderMoved.connect(self.setPosition) self.positionSlider.sliderMoved.connect(self.handleLabel) self.positionSlider.setSingleStep(2) self.positionSlider.setPageStep(20) self.positionSlider.setAttribute(Qt.WA_TranslucentBackground, True) self.clip = QApplication.clipboard() self.process = QProcess(self) self.process.readyRead.connect(self.dataReady) self.process.finished.connect(self.playFromURL) self.myurl = "" # channel list self.channelList = QListView(self) self.channelList.setMinimumSize(QSize(150, 0)) self.channelList.setMaximumSize(QSize(150, 4000)) self.channelList.setFrameShape(QFrame.Box) self.channelList.setObjectName("channelList") self.channelList.setStyleSheet("background-color: black; color: #585858;") self.channelList.setFocus() # for adding items to list must create a model self.model = QStandardItemModel() self.channelList.setModel(self.model) self.controlLayout = QHBoxLayout() self.controlLayout.setContentsMargins(5, 0, 5, 0) self.controlLayout.addWidget(self.playButton) self.controlLayout.addWidget(self.lbl) self.controlLayout.addWidget(self.positionSlider) self.controlLayout.addWidget(self.elbl) self.mainLayout = QHBoxLayout() # contains video and cotrol widgets to the left side self.layout = QVBoxLayout() self.layout.setContentsMargins(0, 0, 0, 0) self.layout.addWidget(self.videoWidget) self.layout.addLayout(self.controlLayout) # adds channels list to the right self.mainLayout.addLayout(self.layout) self.mainLayout.addWidget(self.channelList) self.setLayout(self.mainLayout) self.myinfo = "©2020\nTIVOpy v1.0" self.widescreen = True #### shortcuts #### self.shortcut = QShortcut(QKeySequence("q"), self) self.shortcut.activated.connect(self.handleQuit) self.shortcut = QShortcut(QKeySequence("u"), self) self.shortcut.activated.connect(self.playFromURL) self.shortcut = QShortcut(QKeySequence(Qt.Key_Space), self) self.shortcut.activated.connect(self.play) self.shortcut = QShortcut(QKeySequence(Qt.Key_F), self) self.shortcut.activated.connect(self.handleFullscreen) self.shortcut = QShortcut(QKeySequence(Qt.Key_Escape), self) self.shortcut.activated.connect(self.exitFullscreen) self.shortcut.activated.connect(self.handleFullscreen) self.shortcut = QShortcut(QKeySequence("i"), self) self.shortcut.activated.connect(self.handleInfo) self.shortcut = QShortcut(QKeySequence("s"), self) self.shortcut.activated.connect(self.toggleSlider) self.shortcut = QShortcut(QKeySequence(Qt.Key_Right), self) self.shortcut.activated.connect(self.forwardSlider) self.shortcut = QShortcut(QKeySequence(Qt.Key_Left), self) self.shortcut.activated.connect(self.backSlider) self.mediaPlayer.setVideoOutput(self.videoWidget) self.mediaPlayer.stateChanged.connect(self.mediaStateChanged) self.mediaPlayer.positionChanged.connect(self.positionChanged) self.mediaPlayer.positionChanged.connect(self.handleLabel) self.mediaPlayer.durationChanged.connect(self.durationChanged) self.mediaPlayer.error.connect(self.handleError) self.populateChannelList() self.selectChannel() self.initialPlay()
def addShortCut(widget, keycode, callback): if isinstance(keycode, str): keycode = ord(keycode) keyseq = QtGui.QKeySequence(keycode) short = QShortcut(keyseq, widget) short.activated.connect(callback)
def create_widget_instance(self, node): """ Create a OWWidget instance for the node. """ desc = node.description klass = name_lookup(desc.qualified_name) log.info("Creating %r instance.", klass) widget = klass.__new__(klass, None, signal_manager=self.signal_manager(), stored_settings=node.properties) # Init the node/widget mapping and state before calling __init__ # Some OWWidgets might already send data in the constructor # (should this be forbidden? Raise a warning?) triggering the signal # manager which would request the widget => node mapping or state self.__widget_for_node[node] = widget self.__node_for_widget[widget] = node self.__widget_processing_state[widget] = 0 widget.__init__() widget.setCaption(node.title) widget.widgetInfo = desc widget.setWindowIcon(icon_loader.from_description(desc).get(desc.icon)) widget.setVisible(node.properties.get("visible", False)) node.title_changed.connect(widget.setCaption) # Widget's info/warning/error messages. widget.widgetStateChanged.connect(self.__on_widget_state_changed) # Widget's statusTip node.set_status_message(widget.statusMessage()) widget.statusMessageChanged.connect(node.set_status_message) # Widget's progress bar value state. widget.progressBarValueChanged.connect(node.set_progress) # Widget processing state (progressBarInit/Finished) # and the blocking state. widget.processingStateChanged.connect( self.__on_processing_state_changed) widget.blockingStateChanged.connect(self.__on_blocking_state_changed) if widget.isBlocking(): # A widget can already enter blocking state in __init__ self.__widget_processing_state[widget] |= self.BlockingUpdate if widget.processingState != 0: # It can also start processing (initialization of resources, ...) self.__widget_processing_state[widget] |= self.ProcessingUpdate node.set_processing_state(1) node.set_progress(widget.progressBarValue) # Install a help shortcut on the widget help_shortcut = QShortcut(QKeySequence("F1"), widget) help_shortcut.activated.connect(self.__on_help_request) # Up shortcut (activate/open parent) up_shortcut = QShortcut(QKeySequence(Qt.ControlModifier + Qt.Key_Up), widget) up_shortcut.activated.connect(self.__on_activate_parent) owactions = [ action for action in widget.actions() if isinstance(action, OWAction) ] node.setProperty("ext-menu-actions", owactions) return widget
def submenu_and_function(instance_, object_, func_, shortcut_=None): if shortcut_ is not None: s_ = QShortcut(QtGui.QKeySequence(shortcut_), instance_) s_.activated.connect(func_) object_.triggered.connect(func_)
def __init__(self, controller: 'Controller') -> None: super().__init__() self.controller = controller self.is_unused = True self.set_unused_text() self.returnPressed.connect(self.on_return_pressed) self.history: List[str] = [] self.history_idx = 0 action = self.addAction(QIcon.fromTheme("window-close"), QLineEdit.TrailingPosition) action.triggered.connect(self._on_reset) action.setToolTip("Close the Search") shortcut = QShortcut(QKeySequence(Qt.CTRL + Qt.Key_G), self) shortcut.setContext(Qt.WidgetShortcut) shortcut.activated.connect(self._on_reset) shortcut = QShortcut(QKeySequence(Qt.Key_Escape), self) shortcut.setContext(Qt.WidgetShortcut) shortcut.activated.connect(self._on_reset) shortcut = QShortcut(QKeySequence(Qt.Key_Up), self) shortcut.setContext(Qt.WidgetShortcut) shortcut.activated.connect(self.history_up) shortcut = QShortcut(QKeySequence(Qt.Key_Down), self) shortcut.setContext(Qt.WidgetShortcut) shortcut.activated.connect(self.history_down)