Example #1
0
 def find_object(self, stc=False):
     target = self.query.text()
     if stc:
         target = f'{self.llc[0]},{self.llc[1]}'
     geocoder_params = {
         "apikey": "40d1649f-0493-4b70-98ba-98533de7710b",
         "geocode": target,
         "format": "json"
     }
     response_toponym = requests.get(self.geocoder_api_server, params=geocoder_params)
     try:
         json_response = response_toponym.json()
         toponym = json_response["response"]["GeoObjectCollection"][
             "featureMember"][0]["GeoObject"]
         toponym_coodrinates = toponym["Point"]["pos"]
         address = toponym['metaDataProperty']['GeocoderMetaData']['Address']['formatted']
         if 'postal_code' in toponym['metaDataProperty']['GeocoderMetaData']['Address']:
             self.postal = toponym['metaDataProperty']['GeocoderMetaData']['Address']['postal_code']
         else:
             self.postal = 'нет почтового индекса'
         if not stc:
             self.ll = tuple(map(float, toponym_coodrinates.split(" ")))
             self.point = f'{self.ll[0]},{self.ll[1]},pm2dgl'
         else:
             self.point = f'{self.llc[0]},{self.llc[1]},pm2dgl'
         self.cur_address = address
         QApplication.focusWidget().clearFocus()
         self.update_pic()
         self.update_address()
     except Exception:
         self.address.setText('Неправильный запрос')
Example #2
0
 def formatSelectAll(self):
     """Select all text in any currently focused editor.
     """
     try:
         QApplication.focusWidget().selectAll()
     except AttributeError:
         pass
Example #3
0
 def keyPressEvent(self, key):
     if (key.key() == Qt.Key_Right or (key.key() == Qt.Key_Return and
         QApplication.focusWidget() == self.next_solution_btm)) and \
             self.next_solution_btm.isEnabled():
         self.next_solution_btm.clicked.emit()
     elif (key.key() == Qt.Key_Left or (key.key() == Qt.Key_Return and
           QApplication.focusWidget() == self.previous_solution_btm)) and \
             self.previous_solution_btm.isEnabled():
         self.previous_solution_btm.clicked.emit()
     elif key.key() == Qt.Key_Escape:
         self.closeEvent(QCloseEvent())
     elif (key.key() == Qt.Key_Return and not isinstance(self, Window)
           and QApplication.focusWidget() == self.exit_button):
         self.exit_button.clicked.emit()
Example #4
0
 def moveTreeItem(self, nStep):
     """Move an item up or down in the tree, but only if the treeView has focus. This also
     applies when the menu is used.
     """
     if QApplication.focusWidget() == self and self.theParent.hasProject:
         tHandle = self.getSelectedHandle()
         tItem = self._getTreeItem(tHandle)
         pItem = tItem.parent()
         if pItem is None:
             tIndex = self.indexOfTopLevelItem(tItem)
             nChild = self.topLevelItemCount()
             nIndex = tIndex + nStep
             if nIndex < 0 or nIndex >= nChild:
                 return False
             cItem = self.takeTopLevelItem(tIndex)
             self.insertTopLevelItem(nIndex, cItem)
         else:
             tIndex = pItem.indexOfChild(tItem)
             nChild = pItem.childCount()
             nIndex = tIndex + nStep
             if nIndex < 0 or nIndex >= nChild:
                 return False
             cItem = pItem.takeChild(tIndex)
             pItem.insertChild(nIndex, cItem)
         self.clearSelection()
         cItem.setSelected(True)
         self.theProject.setProjectChanged(True)
     else:
         return False
     return True
Example #5
0
    def fuzzy_search_action(self):
        """Open a dialog for quick access to actions
        with fuzzy search."""
        focussed_widget = QApplication.focusWidget()
        self.fuzzy_search_ui.ui.fuzzy_search_field.setFocus()

        def get_data(model):
            plugins = [x[1].name for x in self.plugins.available_plugins]
            for p in self.plugins.codecs + \
                     self.plugins.compressions +\
                     self.plugins.assemblies:
                plugins.append('-' + p[1].name)
                plugins.extend(['-' + x for x in p[1].aliases])
            for p in self.plugins.available_plugins:
                plugins.extend(p[1].aliases)
            model.setStringList(plugins)

        completer = QCompleter()
        self.fuzzy_search_ui.ui.fuzzy_search_field.setCompleter(completer)
        model = QStringListModel()
        completer.setModel(model)
        get_data(model)
        if self.fuzzy_search_ui.exec_() == 0:
            return
        search_data = self.fuzzy_search_ui.ui.fuzzy_search_field.text()
        parent_encoder = self.get_parent_encoder(focussed_widget)
        if parent_encoder:
            parent_encoder.action_fuzzy(search_data)
        else:
            LOGGER.error('Unable to find parent encoder for ' +
                         str(focussed_widget))
Example #6
0
 def splitterMoved(self, pos, index):
     """Avoid segfault when QListWidget has focus and
     is going to be collapsed.
     """
     focusedWidget = QApplication.focusWidget()
     if focusedWidget:
         focusedWidget.clearFocus()
Example #7
0
 def _change_tab_index(self):
     """Change the tabs of the current TabWidget using alt+numbers."""
     widget = QApplication.focusWidget()
     shortcut_index = getattr(widget, 'shortcut_index', None)
     if shortcut_index:
         obj = self.sender()
         shortcut_index(obj.index)
Example #8
0
 def _change_tab_index(self):
     """Change the tabs of the current TabWidget using alt+numbers."""
     widget = QApplication.focusWidget()
     shortcut_index = getattr(widget, 'shortcut_index', None)
     if shortcut_index:
         obj = self.sender()
         shortcut_index(obj.index)
Example #9
0
 def handle_button_clicked(self):
     button = QApplication.focusWidget()
     index = self.table.indexAt(button.pos())
     if index.isValid():
         i = int(index.row())
         modality = self.table.item(i, 2).text()
         self.show_edit(i, modality)
Example #10
0
 def splitterMoved(self, pos, index):
     """Avoid segfault when QListWidget has focus and
     is going to be collapsed.
     """
     focusedWidget = QApplication.focusWidget()
     if focusedWidget:
         focusedWidget.clearFocus()
Example #11
0
    def accept(self):
        # Un-focus the currently focused widget to ensure that it's data validators were checked.
        focusWidget = QApplication.focusWidget()
        if focusWidget is not None:
            focusWidget.clearFocus()

        # Can't accept if there are errors.
        if len(self._error_fields) > 0:
            msg = "Error: Invalid data in the following fields:\n"
            for field in self._error_fields:
                msg += field + '\n'
            QMessageBox.warning(self, "Error", msg)
            return

        # Inspect the user's changes to see if we need to warn about anything.
        closing_messages = self._getClosingMessages()

        if not self._applyTempOpSettingsRealOp():
            return
        else:
            # Success.  Close the dialog.
            for title, msg in closing_messages:
                QMessageBox.information(self, title, msg)
            self._tearDownEventFilters()
            self._cleanUpTempOperators()
            super(DatasetInfoEditorWidget, self).accept()
Example #12
0
 def keyPressEvent(self, event):
     '''
     @param: event QKeyEvent
     '''
     evkey = event.key()
     evmodifiers = event.modifiers()
     if evkey == Qt.Key_Tab or evkey == Qt.Key_Backtab and \
             self.count() > 1 and evmodifiers & Qt.ControlModifier:
         pageCount = self.count()
         page = self.currentIndex()
         if (evkey == Qt.Key_Backtab) or (evmodifiers & Qt.ShiftModifier):
             dx = -1
         else:
             dx = 1
         for idx in range(pageCount):
             page += dx
             if page < 0:
                 page = self.count() - 1
             elif page >= pageCount:
                 page = 0
             if self._tabBar.isTabEnabled(page):
                 self.setCurrentIndex(page)
                 break
         if not QApplication.focusWidget():
             self._tabBar.setFocus()
     else:
         event.ignore()
Example #13
0
 def mousePressEvent(self, a0: QtGui.QMouseEvent) -> None:
     """
     Overrides QDialog to detect click events. Used mainly to clear focus from QLineEdits.
     """
     # pylint: disable=c-extension-no-member, no-self-use
     focused_widget = QApplication.focusWidget()
     if isinstance(focused_widget, QLineEdit):
         focused_widget.clearFocus()
Example #14
0
 def open_path():
     button = QApplication.focusWidget()
     index = tableWidget.indexAt(button.pos())
     location = str(tableWidget.item(index.row(), 0).text())
     system = platform.system()
     if system == "Linux":
         os.system('xdg-open "%s"' % location)
     else:
         os.startfile(location)
Example #15
0
 def pop(self) -> None:
     """_summary_
     """
     widget = QApplication.focusWidget().parent()
     for idx in range(self.count()):
         if self.itemAt(idx).widget() == widget:
             self.removeWidget(widget)
             widget.deleteLater()
             self.pop_marker_from_text(idx + 1)
             break
Example #16
0
 def toggle_next_encoder_focus(self):
     """Focus the next encoder widget."""
     focussed_widget = QApplication.focusWidget()
     parent_encoder = self.get_parent_encoder(focussed_widget)
     if parent_encoder:
         if parent_encoder.has_next():
             parent_encoder.next.field.setFocus()
             self.ui.DeenMainWindow.ensureWidgetVisible(parent_encoder.next)
     else:
         LOGGER.error('Unable to find parent encoder for ' +
                      str(focussed_widget))
Example #17
0
 def toggle_search_box_visibility(self):
     """Toggle the search box visibility
     via a shortcut for the current encoder
     widget."""
     focussed_widget = QApplication.focusWidget()
     parent_encoder = self.get_parent_encoder(focussed_widget)
     if parent_encoder:
         parent_encoder.toggle_search_box_visibility()
     else:
         LOGGER.error('Unable to find parent encoder for ' +
                      str(focussed_widget))
Example #18
0
 def _focused_widget_ancestor_index(self, widget):
     """
     If widget is an ancestor (parent, parent-parent, etc.) of the
     currently focused widget, return the number of parent steps
     between widget and the focused widget.  Otherwise, return None.
     """
     focused_widget = QApplication.focusWidget()
     ancestors = self._get_ancestors(focused_widget)
     try:
         return ancestors.index(widget)
     except ValueError:
         return None
Example #19
0
 def _focused_widget_ancestor_index(self, widget):
     """
     If widget is an ancestor (parent, parent-parent, etc.) of the
     currently focused widget, return the number of parent steps
     between widget and the focused widget.  Otherwise, return None.
     """
     focused_widget = QApplication.focusWidget()
     ancestors = self._get_ancestors(focused_widget)
     try:
         return ancestors.index(widget)
     except ValueError:
         return None
Example #20
0
    def mousePressEvent(self, event):
        """
        Clear the focus of the text boxes if somewhere
        else on the window is clicked
        """

        focused = QApplication.focusWidget()
        if focused == self.missionBox:
            self.missionBox.clearFocus()
        if focused == self.adviceBox:
            self.adviceBox.clearFocus()
        QMainWindow.mousePressEvent(self, event)
Example #21
0
    def mousePressEvent(self, event):
        """
        Clear the focus of the text boxes and buttons if somewhere
        else on the window is clicked
        """

        # Get the object currently in focus
        focused = QApplication.focusWidget()

        if isinstance(focused, (QPushButton, QTextEdit)):
            focused.clearFocus()

        QMainWindow.mousePressEvent(self, event)
Example #22
0
    def initUI(self):
        #self._layout = QHBoxLayout(self)
        self._widget = QWidget(self)
        #self._layout.addWidget(self._widget)
        self._menuBar = QMenuBar(self._widget)

        exitAct = QAction(QIcon('exit.png'), '&Exit', self)
        exitAct.setShortcut('Ctrl+Q')
        exitAct.setStatusTip('Exit application')
        exitAct.triggered.connect(qApp.quit)

        self.statusBar()

        #menubar = self.menuBar()
        menubar = self._menuBar
        fileMenu = menubar.addMenu('&File')
        fileMenu.addAction(exitAct)

        act = self._menuBar.addAction('test')
        act.setShortcut(QKeySequence('Ctrl+M'))

        def testCb():
            print('hello')

        act.triggered.connect(testCb)
        act.setShortcutContext(Qt.WidgetShortcut)
        print('_menuBar parent', self._menuBar.parent())
        print('act parent', act.parent())
        print('_widget parent', self._widget.parent())
        #act.setParent(self)
        #print(act.parent())
        self.addAction(act)
        # This is important for Qt.WidgetShortcut
        # the Example is focused, and it's menu's act can trigger
        # Qt.WidgetShortcut context action
        #self.setFocus()
        #act.parent().setFocus()
        print('focusWidget', QApplication.focusWidget())

        def cb():
            tt = QApplication.focusWidget()
            print(tt)

        from PyQt5.Qt import QShortcut
        self.short0 = QShortcut(QKeySequence('Ctrl+N'), self)
        self.short0.activated.connect(cb)

        self.setGeometry(300, 300, 300, 200)
        self.setWindowTitle('Simple menu')
        self.show()
Example #23
0
 def copy_content_to_clipboard(self):
     focussed_widget = QApplication.focusWidget()
     parent_encoder = self.get_parent_encoder(focussed_widget)
     if not parent_encoder._content:
         return
     try:
         content = parent_encoder._content.decode('utf8')
     except UnicodeDecodeError as e:
         parent_encoder.log.error(
             'Cannot copy non-ASCII content to clipboard')
         parent_encoder.log.debug(e, exc_info=True)
         return
     clipboard = QApplication.clipboard()
     clipboard.setText(content)
Example #24
0
 def clear_current_widget(self):
     """Clear and remove the current encoder widget."""
     focussed_widget = QApplication.focusWidget()
     if not hasattr(focussed_widget, 'parent') or \
             not focussed_widget.parent:
         LOGGER.warning('NO parent for widget found: ' +
                        str(focussed_widget))
         return
     if callable(focussed_widget.parent):
         widget = focussed_widget.parent()
     else:
         widget = focussed_widget.parent
     if isinstance(widget, DeenEncoderWidget):
         widget.clear_content()
Example #25
0
 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()
Example #26
0
    def change_focus(cls):

        # TODO: other widget can add themselves to focusable_widgets
        focusable_widgets = [
            ViewOp.ui.WEBVIEW.tracks_table_widget, _BaseItem.items[2]
        ]

        current_focus_widget = QApplication.focusWidget()
        if current_focus_widget in focusable_widgets:
            index = focusable_widgets.index(current_focus_widget)
            next_index = index + 1 if index < (len(focusable_widgets) - 1)\
                else 0
            focusable_widgets[next_index].setFocus()
        else:
            focusable_widgets[0].setFocus()
Example #27
0
    def change_focus(cls):

        # TODO: other widget can add themselves to focusable_widgets
        focusable_widgets = [
            ViewOp.ui.WEBVIEW.tracks_table_widget,
            _BaseItem.items[2]]

        current_focus_widget = QApplication.focusWidget()
        if current_focus_widget in focusable_widgets:
            index = focusable_widgets.index(current_focus_widget)
            next_index = index + 1 if index < (len(focusable_widgets) - 1)\
                else 0
            focusable_widgets[next_index].setFocus()
        else:
            focusable_widgets[0].setFocus()
Example #28
0
    def add_field_widgets(self):
        # Before clearing previous field widgets, remove focus from whatever
        # widget we might be focused on right now. If focus runs between the
        # old elements as they're getting deleted, that can cause problems with
        # focus-based signals like editingFinished.
        focused_widget = QApplication.focusWidget()
        if focused_widget:
            focused_widget.clearFocus()

        # Clear field widgets added from the previous input GCI. We do
        # this because each widget set is specific to a particular GCI type
        # (replay, ghost, etc.)
        clear_qlayout(self.fields_vbox)

        for field in self.fields:
            self.add_field_widget(field, self.fields_vbox)
Example #29
0
    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()
Example #30
0
        def ass_value():

            '''[Gabriele] Get column and row of clicked widget in table '''

            clicked = QApplication.focusWidget().pos()
            index = self.AssignTable.indexAt(clicked)
            col = index.column()
            row = index.row()
            sel_combo = self.AssignTable.cellWidget(row, col)  # [Gabriele] Combobox @ row and column

            '''[Gabriele] Use a dict to rename the columns. The keys are the column index of the original df while the values are the new names. '''


            items = list(self.rename_dict.values())
            if sel_combo.currentText() in items and sel_combo.currentText() != 'N.a.':
                print('Item already assigned')
            else:
                self.rename_dict[row] = sel_combo.currentText()
            self.preview_file(self.input_data_df)
Example #31
0
 def save_widget_content_to_file(self, file_name=None):
     """Save the content of the current widget
     to a file."""
     focussed_widget = QApplication.focusWidget()
     parent_encoder = self.get_parent_encoder(focussed_widget)
     if not parent_encoder._content:
         return
     fd = QFileDialog(parent_encoder)
     if file_name:
         name = file_name
     else:
         name = fd.getSaveFileName(fd, 'Save File')
     if not name or not name[0]:
         return
     if isinstance(name, tuple):
         name = name[0]
     with open(name, 'wb') as file:
         current_plugin = parent_encoder.plugin
         file.write(parent_encoder._content)
Example #32
0
 def mousePressEvent(self, event):
     try:
         focused_widget = QApplication.focusWidget()
         if isinstance(focused_widget, QLineEdit):
             focused_widget.clearFocus()
         QMainWindow.mousePressEvent(self, event)
         point = get_click([event.pos().x(), event.pos().y()])
         if event.button() == 1:
             get_address(",".join(list(map(str, point))))
             self.index.setText(GameData.postal_index)
         elif event.button() == 2:
             point = get_organization(",".join(list(map(str, point))))
             if not point:
                 GameData.points = []
                 self.check(coord_set=True)
         if point:
             GameData.points = [point]
             self.check(coord_set=True)
     except Exception as e:
         QMessageBox.about(self, "error", str(e))
Example #33
0
    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 accept(self):
        # Un-focus the currently focused widget to ensure that it's data validators were checked.
        focusWidget = QApplication.focusWidget()
        if focusWidget is not None:
            focusWidget.clearFocus()            
        
        # Can't accept if there are errors.
        if len(self._error_fields) > 0:
            msg = "Error: Invalid data in the following fields:\n"
            for field in self._error_fields:
                msg += field + '\n'
            QMessageBox.warning(self, "Error", msg)
            return

        # Inspect the user's changes to see if we need to warn about anything.
        closing_messages = self._getClosingMessages()
        self.encountered_exception = self._applyTempOpSettingsRealOp()

        # Close the dialog.
        for title, msg in closing_messages:
            QMessageBox.information(self, title, msg)
        self._tearDownEventFilters()
        self._cleanUpTempOperators()
        super(DatasetInfoEditorWidget, self).accept()
Example #35
0
 def change_focus(cls):
     if QApplication.focusWidget() is ViewOp.ui.WEBVIEW:
         _BaseItem.items[1].setFocus()
     else:
         ViewOp.ui.WEBVIEW.setFocus()
Example #36
0
    def tabopen(
        self,
        url: QUrl = None,
        background: bool = None,
        related: bool = True,
        idx: int = None,
    ) -> browsertab.AbstractTab:
        """Open a new tab with a given URL.

        Inner logic for open-tab and open-tab-bg.
        Also connect all the signals we need to _filter_signals.

        Args:
            url: The URL to open as QUrl or None for an empty tab.
            background: Whether to open the tab in the background.
                        if None, the `tabs.background` setting decides.
            related: Whether the tab was opened from another existing tab.
                     If this is set, the new position might be different. With
                     the default settings we handle it like Chromium does:
                         - Tabs from clicked links etc. are to the right of
                           the current (related=True).
                         - Explicitly opened tabs are at the very right
                           (related=False)
            idx: The index where the new tab should be opened.

        Return:
            The opened WebView instance.
        """
        if url is not None:
            qtutils.ensure_valid(url)
        log.webview.debug("Creating new tab with URL {}, background {}, "
                          "related {}, idx {}".format(url, background, related,
                                                      idx))

        prev_focus = QApplication.focusWidget()

        if config.val.tabs.tabs_are_windows and self.widget.count() > 0:
            window = mainwindow.MainWindow(private=self.is_private)
            window.show()
            tabbed_browser = objreg.get('tabbed-browser',
                                        scope='window',
                                        window=window.win_id)
            return tabbed_browser.tabopen(url=url,
                                          background=background,
                                          related=related)

        tab = browsertab.create(win_id=self._win_id,
                                private=self.is_private,
                                parent=self.widget)
        self._connect_tab_signals(tab)

        if idx is None:
            idx = self._get_new_tab_idx(related)
        self.widget.insertTab(idx, tab, "")

        if url is not None:
            tab.load_url(url)

        if background is None:
            background = config.val.tabs.background
        if background:
            # Make sure the background tab has the correct initial size.
            # With a foreground tab, it's going to be resized correctly by the
            # layout anyways.
            tab.resize(self.widget.currentWidget().size())
            self.widget.tab_index_changed.emit(self.widget.currentIndex(),
                                               self.widget.count())
            # Refocus webview in case we lost it by spawning a bg tab
            self.widget.currentWidget().setFocus()
        else:
            self.widget.setCurrentWidget(tab)

        mode = modeman.instance(self._win_id).mode
        if mode in [
                usertypes.KeyMode.command, usertypes.KeyMode.prompt,
                usertypes.KeyMode.yesno
        ]:
            # If we were in a command prompt, restore old focus
            # The above commands need to be run to switch tabs
            if prev_focus is not None:
                prev_focus.setFocus()

        tab.show()
        self.new_tab.emit(tab, idx)
        return tab
 def mousePressEvent(self, event):
     focused_widget = QApplication.focusWidget()
     if isinstance(focused_widget, QLineEdit):
         focused_widget.clearFocus()
    def on_customContextMenuRequested(self, pos):

        w.processEvents()
        table = QApplication.focusWidget()
        tableName = table.objectName()

        if table.rowCount() <= 0:
            return

        def getItemData(itemIndex):
            data = []

            for i in range(table.columnCount()):
                try:
                    data.append(table.item(itemIndex, i).text())
                except:
                    pass

            return data
        
        top_menu = QMenu(self)
        menu = top_menu.addMenu("Menu")

        copy = menu.addAction("Copy")
        menu.addSeparator()
        if self.ui.searchForCombo.currentText() == "TV-Show":
            _open = menu.addAction("Open in Bittorren Client")
            menu.addSeparator()
        elif self.ui.searchForCombo.currentText() == "Movie":
            _open = menu.addAction("Open in Bittorren Client")
            menu.addSeparator()
        elif self.ui.searchForCombo.currentText() == "Anime":
            _open = menu.addAction("Open in Bittorren Client")
            menu.addSeparator()
        elif self.ui.searchForCombo.currentText() == "Subtitles":
            _open = menu.addAction("Open in Bittorren Client")
            menu.addSeparator()
        elif self.ui.searchForCombo.currentText() == "All Categories":
            _open = menu.addAction("Open in Bittorren Client")
            menu.addSeparator()
        
        action = menu.exec_(QtGui.QCursor.pos())

        if action == copy:
            item_row = table.currentIndex().row()
            itemName = table.item(item_row, 0).text()
            itemData = getItemData(item_row)

            magnet_link = itemData[3]

            # copy selected path to clipboard
            clipboard = QApplication.clipboard()
            clipboard.setText(magnet_link)
        
        elif action == _open:

            item_row = table.currentIndex().row()
            itemName = table.item(item_row, 0).text()
            itemData = getItemData(item_row)

            magnet_link = itemData[3]

            webbrowser.open_new_tab(magnet_link)

            ## Move Spin-Box episode by one value up and higlight
            self.ui.episodeSpin.setValue(self.ui.episodeSpin.value()+1)
            self.ui.episodeSpin.selectAll()
Example #39
0
    def tabopen(self, url=None, background=None, related=True, idx=None, *,
                ignore_tabs_are_windows=False):
        """Open a new tab with a given URL.

        Inner logic for open-tab and open-tab-bg.
        Also connect all the signals we need to _filter_signals.

        Args:
            url: The URL to open as QUrl or None for an empty tab.
            background: Whether to open the tab in the background.
                        if None, the `tabs.background_tabs`` setting decides.
            related: Whether the tab was opened from another existing tab.
                     If this is set, the new position might be different. With
                     the default settings we handle it like Chromium does:
                         - Tabs from clicked links etc. are to the right of
                           the current (related=True).
                         - Explicitly opened tabs are at the very right
                           (related=False)
            idx: The index where the new tab should be opened.
            ignore_tabs_are_windows: If given, never open a new window, even
                                     with tabs.tabs_are_windows set.

        Return:
            The opened WebView instance.
        """
        if url is not None:
            qtutils.ensure_valid(url)
        log.webview.debug("Creating new tab with URL {}, background {}, "
                          "related {}, idx {}".format(
                              url, background, related, idx))

        prev_focus = QApplication.focusWidget()

        if (config.val.tabs.tabs_are_windows and self.widget.count() > 0 and
                not ignore_tabs_are_windows):
            window = mainwindow.MainWindow(private=self.private)
            window.show()
            tabbed_browser = objreg.get('tabbed-browser', scope='window',
                                        window=window.win_id)
            return tabbed_browser.tabopen(url=url, background=background,
                                          related=related)

        tab = browsertab.create(win_id=self._win_id, private=self.private,
                                parent=self.widget)
        self._connect_tab_signals(tab)

        if idx is None:
            idx = self._get_new_tab_idx(related)
        self.widget.insertTab(idx, tab, "")

        if url is not None:
            tab.openurl(url)

        if background is None:
            background = config.val.tabs.background
        if background:
            # Make sure the background tab has the correct initial size.
            # With a foreground tab, it's going to be resized correctly by the
            # layout anyways.
            tab.resize(self.widget.currentWidget().size())
            self.widget.tab_index_changed.emit(self.widget.currentIndex(),
                                               self.widget.count())
            # Refocus webview in case we lost it by spawning a bg tab
            self.widget.currentWidget().setFocus()
        else:
            self.widget.setCurrentWidget(tab)
            # WORKAROUND for https://bugreports.qt.io/browse/QTBUG-68076
            # Still seems to be needed with Qt 5.11.1
            tab.setFocus()

        mode = modeman.instance(self._win_id).mode
        if mode in [usertypes.KeyMode.command, usertypes.KeyMode.prompt,
                    usertypes.KeyMode.yesno]:
            # If we were in a command prompt, restore old focus
            # The above commands need to be run to switch tabs
            if prev_focus is not None:
                prev_focus.setFocus()

        tab.show()
        self.new_tab.emit(tab, idx)
        return tab