Python PyQt5.QtWidgets.QApplication.clipboard() Examples

The following are 30 code examples of PyQt5.QtWidgets.QApplication.clipboard(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module PyQt5.QtWidgets.QApplication , or try the search function .
Example #1
Source File: screenshot.py    From screenshot with GNU General Public License v3.0 20 votes vote down vote up
def saveScreenshot(self, clipboard=False, fileName='screenshot.png', picType='png'):
        fullWindow = QRect(0, 0, self.width() - 1, self.height() - 1)
        selected = QRect(self.selected_area)
        if selected.left() < 0:
            selected.setLeft(0)
        if selected.right() >= self.width():
            selected.setRight(self.width() - 1)
        if selected.top() < 0:
            selected.setTop(0)
        if selected.bottom() >= self.height():
            selected.setBottom(self.height() - 1)

        source = (fullWindow & selected)
        source.setTopLeft(QPoint(source.topLeft().x() * self.scale, source.topLeft().y() * self.scale))
        source.setBottomRight(QPoint(source.bottomRight().x() * self.scale, source.bottomRight().y() * self.scale))
        image = self.screenPixel.copy(source)

        if clipboard:
            QGuiApplication.clipboard().setImage(QImage(image), QClipboard.Clipboard)
        else:
            image.save(fileName, picType, 10)
        self.target_img = image
        self.screen_shot_grabed.emit(QImage(image)) 
Example #2
Source File: telemetry.py    From sparrow-wifi with GNU General Public License v3.0 6 votes vote down vote up
def createTable(self):
        # Set up location table
        self.locationTable = QTableWidget(self)
        self.locationTable.setColumnCount(8)
        self.locationTable.setGeometry(10, 10, self.geometry().width()/2-20, self.geometry().height()/2)
        self.locationTable.setShowGrid(True)
        self.locationTable.setHorizontalHeaderLabels(['macAddr','SSID', 'Strength', 'Timestamp','GPS', 'Latitude', 'Longitude', 'Altitude'])
        self.locationTable.resizeColumnsToContents()
        self.locationTable.setRowCount(0)
        self.locationTable.horizontalHeader().setSectionResizeMode(1, QHeaderView.Stretch)
        
        self.ntRightClickMenu = QMenu(self)
        newAct = QAction('Copy', self)        
        newAct.setStatusTip('Copy data to clipboard')
        newAct.triggered.connect(self.onCopy)
        self.ntRightClickMenu.addAction(newAct)
        
        self.locationTable.setContextMenuPolicy(Qt.CustomContextMenu)
        self.locationTable.customContextMenuRequested.connect(self.showNTContextMenu) 
Example #3
Source File: fygui.py    From dayworkspace with GNU Lesser General Public License v3.0 6 votes vote down vote up
def fanyi(self):
        if time.time() - self.time < 0.1:
            print("停一下")
            return
        self.time = time.time()
        if self.ui.textEdit.hasFocus():
            return
        text = self.clipboard.text(self.clipboard.Selection)
        if len(text) > 20:
            return
        self.mainWindow.move(*self._position())
        texttmp = ""
        for c in text:
            if c.isupper():
                texttmp += " " + c
            else:
                texttmp += c
        text = texttmp
        text = text.strip(' ')
        if text != '':
            text = self.wordutil.execfind(text)
            self.ui.textEdit.clear()
            self.ui.textEdit.insertHtml(text) 
Example #4
Source File: fygui.py    From dayworkspace with GNU Lesser General Public License v3.0 6 votes vote down vote up
def __init__(self):
        self.app = QApplication(sys.argv)
        self.mainWindow = QMainWindow()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self.mainWindow)

        self.Dialog = QtWidgets.QDialog()
        self.ui2 = Ui_Form()
        self.ui2.setupUi(self.Dialog)

        self.ui.textEdit.setReadOnly(True)
        self.clipboard = QApplication.clipboard()
        self.clipboard.selectionChanged.connect(self.fanyi)
        self.mainWindow.setWindowTitle("划词翻译")
        self.mainWindow.setWindowFlags(QtCore.Qt.WindowStaysOnTopHint)
        self.ui2.lineEdit.editingFinished.connect(self.callInput)
        self.Dialog.moveEvent = self.mainMove
        self.wordutil = wordutil()
        self.time = time.time()
        self.ui.textEdit.mouseDoubleClickEvent = self.inputText 
Example #5
Source File: paperTran.py    From paper-translator with MIT License 6 votes vote down vote up
def __init__(self, sender, parent=None):
        super().__init__(parent)
        self.editor = sender
        self.form = parent
        self.timer = QTimer()
        self.timer.setInterval(TRANS_INTERVAL)
        self.timer.start()
        # 信号连接到槽
        self.timer.timeout.connect(self.onTimerOut)
        self.lastTran = ''
        self.lastTranWord = ''
        self.clipboard = QApplication.clipboard()

        self.storeTimer = QTimer()
        self.storeTimer.setInterval(STORE_INTERVAL)
        self.storeTimer.start()
        self.timer.timeout.connect(self.restoreTimeOut)

    # 定义槽 
Example #6
Source File: eventfilter.py    From legion with GNU General Public License v3.0 6 votes vote down vote up
def filterKeyPressInHostsTableView(self, key, receiver):
        if not receiver.selectionModel().selectedRows():
            return True

        index = receiver.selectionModel().selectedRows()[0].row()

        if key == Qt.Key_Down:
            new_index = index + 1
            receiver.selectRow(new_index)
            receiver.clicked.emit(receiver.selectionModel().selectedRows()[0])
        elif key == Qt.Key_Up:
            new_index = index - 1
            receiver.selectRow(new_index)
            receiver.clicked.emit(receiver.selectionModel().selectedRows()[0])
        elif QApplication.keyboardModifiers() == Qt.ControlModifier and key == Qt.Key_C:
            selected = receiver.selectionModel().currentIndex()
            clipboard = QApplication.clipboard()
            clipboard.setText(selected.data().toString())
        return True 
Example #7
Source File: scripting.py    From autokey with GNU General Public License v3.0 6 votes vote down vote up
def get_selection(self):
        """
        Read text from the X selection
        
        Usage: C{clipboard.get_selection()}

        @return: text contents of the mouse selection
        @rtype: C{str}
        @raise Exception: if no text was found in the selection
        """
        Gdk.threads_enter()
        text = self.selection.wait_for_text()
        Gdk.threads_leave()
        if text is not None:
            return text
        else:
            raise Exception("No text found in X selection") 
Example #8
Source File: interface.py    From autokey with GNU General Public License v3.0 6 votes vote down vote up
def send_string_clipboard(self, string: str, paste_command: model.SendMode):
        """
        This method is called from the IoMediator for Phrase expansion using one of the clipboard method.
        :param string: The to-be pasted string
        :param paste_command: Optional paste command. If None, the mouse selection is used. Otherwise, it contains a
         keyboard combination string, like '<ctrl>+v', or '<shift>+<insert>' that is sent to the target application,
         causing a paste operation to happen.
        """
        logger.debug("Sending string via clipboard: " + string)
        if common.USING_QT:
            if paste_command is None:
                self.__enqueue(self.app.exec_in_main, self._send_string_selection, string)
            else:
                self.__enqueue(self.app.exec_in_main, self._send_string_clipboard, string, paste_command)
        else:
            if paste_command is None:
                self.__enqueue(self._send_string_selection, string)
            else:
                self.__enqueue(self._send_string_clipboard, string, paste_command)
        logger.debug("Sending via clipboard enqueued.") 
Example #9
Source File: telemetry.py    From sparrow-wifi with GNU General Public License v3.0 6 votes vote down vote up
def createTable(self):
        # Set up location table
        self.locationTable = QTableWidget(self)
        self.locationTable.setColumnCount(10)
        self.locationTable.setGeometry(10, 10, self.geometry().width()/2-20, self.geometry().height()/2)
        self.locationTable.setShowGrid(True)
        self.locationTable.setHorizontalHeaderLabels(['macAddr','Name', 'RSSI', 'TX Power', 'Est Range (m)', 'Timestamp','GPS', 'Latitude', 'Longitude', 'Altitude'])
        self.locationTable.resizeColumnsToContents()
        self.locationTable.setRowCount(0)
        self.locationTable.horizontalHeader().setSectionResizeMode(1, QHeaderView.Stretch)
        
        self.ntRightClickMenu = QMenu(self)
        newAct = QAction('Copy', self)        
        newAct.setStatusTip('Copy data to clipboard')
        newAct.triggered.connect(self.onCopy)
        self.ntRightClickMenu.addAction(newAct)
        
        self.locationTable.setContextMenuPolicy(Qt.CustomContextMenu)
        self.locationTable.customContextMenuRequested.connect(self.showNTContextMenu) 
Example #10
Source File: telemetry.py    From sparrow-wifi with GNU General Public License v3.0 6 votes vote down vote up
def onCopy(self):
        self.updateLock.acquire()
        
        curRow = self.locationTable.currentRow()
        curCol = self.locationTable.currentColumn()
        
        if curRow == -1 or curCol == -1:
            self.updateLock.release()
            return
        
        curText = self.locationTable.item(curRow, curCol).text()
            
        clipboard = QApplication.clipboard()
        clipboard.setText(curText)
        
        self.updateLock.release() 
Example #11
Source File: sparrow-wifi.py    From sparrow-wifi with GNU General Public License v3.0 6 votes vote down vote up
def onCopyNet(self):
        self.updateLock.acquire()
        
        curRow = self.networkTable.currentRow()
        curCol = self.networkTable.currentColumn()
        
        if curRow == -1 or curCol == -1:
            self.updateLock.release()
            return
        
        if curCol != 11:
            curText = self.networkTable.item(curRow, curCol).text()
        else:
            curNet = self.networkTable.item(curRow, 2).data(Qt.UserRole+1)
            curText = 'Last Recorded GPS Coordinates:\n' + str(curNet.gps)
            curText += 'Strongest Signal Coordinates:\n'
            curText += 'Strongest Signal: ' + str(curNet.strongestsignal) + '\n'
            curText += str(curNet.strongestgps)
            
        clipboard = QApplication.clipboard()
        clipboard.setText(curText)
        
        self.updateLock.release() 
Example #12
Source File: repo_tab.py    From vorta with GNU General Public License v3.0 6 votes vote down vote up
def ssh_copy_to_clipboard_action(self):
        msg = QMessageBox()
        msg.setStandardButtons(QMessageBox.Ok)
        msg.setParent(self, QtCore.Qt.Sheet)

        index = self.sshComboBox.currentIndex()
        if index > 1:
            ssh_key_filename = self.sshComboBox.itemData(index)
            ssh_key_path = os.path.expanduser(f'~/.ssh/{ssh_key_filename}.pub')
            if os.path.isfile(ssh_key_path):
                pub_key = open(ssh_key_path).read().strip()
                clipboard = QApplication.clipboard()
                clipboard.setText(pub_key)

                msg.setText(self.tr("Public Key Copied to Clipboard"))
                msg.setInformativeText(self.tr(
                    "The selected public SSH key was copied to the clipboard. "
                    "Use it to set up remote repo permissions."))

            else:
                msg.setText(self.tr("Couldn't find public key."))
        else:
            msg.setText(self.tr("Select a public key from the dropdown first."))
        msg.exec_() 
Example #13
Source File: source_tab.py    From vorta with GNU General Public License v3.0 6 votes vote down vote up
def paste_text(self):
        sources = QApplication.clipboard().text().splitlines()
        invalidSources = ""
        for source in sources:
            if len(source) > 0:  # Ignore empty newlines
                if not os.path.exists(source):
                    invalidSources = invalidSources + "\n" + source
                else:
                    new_source, created = SourceFileModel.get_or_create(dir=source, profile=self.profile())
                    if created:
                        self.sourceFilesWidget.addItem(source)
                        new_source.save()

        if len(invalidSources) != 0:  # Check if any invalid paths
            msg = QMessageBox()
            msg.setText("Some of your sources are invalid:" + invalidSources)
            msg.exec() 
Example #14
Source File: repo_tab.py    From restatic with GNU General Public License v3.0 6 votes vote down vote up
def ssh_copy_to_clipboard_action(self):
        msg = QMessageBox()
        msg.setStandardButtons(QMessageBox.Ok)
        msg.setParent(self, QtCore.Qt.Sheet)

        index = self.sshComboBox.currentIndex()
        if index > 1:
            ssh_key_filename = self.sshComboBox.itemData(index)
            ssh_key_path = os.path.expanduser(f"~/.ssh/{ssh_key_filename}.pub")
            if os.path.isfile(ssh_key_path):
                pub_key = open(ssh_key_path).read().strip()
                clipboard = QApplication.clipboard()
                clipboard.setText(pub_key)

                msg.setText("Public Key Copied to Clipboard")
                msg.setInformativeText(
                    "The selected public SSH key was copied to the clipboard. "
                    "Use it to set up remote repo permissions."
                )

            else:
                msg.setText("Couldn't find public key.")
        else:
            msg.setText("Select a public key from the dropdown first.")
        msg.exec_() 
Example #15
Source File: screenshot.py    From screenshot with GNU General Public License v3.0 6 votes vote down vote up
def changeAction(self, nextAction):
        QApplication.clipboard().setText('Test in changeAction function')

        if nextAction == ACTION_UNDO:
            self.undoOperation()
        elif nextAction == ACTION_SAVE:
            self.saveOperation()
        elif nextAction == ACTION_CANCEL:
            self.close()
        elif nextAction == ACTION_SURE:
            self.saveToClipboard()

        else:
            self.action = nextAction

        self.setFocus() 
Example #16
Source File: scripting.py    From autokey with GNU General Public License v3.0 5 votes vote down vote up
def get_clipboard(self):
        """
        Read text from the clipboard
        
        Usage: C{clipboard.get_clipboard()}

        @return: text contents of the clipboard
        @rtype: C{str}
        """
        self.__execAsync(self.__getClipboard)
        return str(self.text) 
Example #17
Source File: interface.py    From autokey with GNU General Public License v3.0 5 votes vote down vote up
def selection(self):
        """Get and set the mouse selection clipboard content."""
        return 
Example #18
Source File: interface.py    From autokey with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self):
            self._clipboard = QApplication.clipboard() 
Example #19
Source File: interface.py    From autokey with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, mediator, app):
        threading.Thread.__init__(self)
        self.setDaemon(True)
        self.setName("XInterface-thread")
        self.mediator = mediator  # type: IoMediator
        self.app = app
        self.lastChars = [] # QT4 Workaround
        self.__enableQT4Workaround = False # QT4 Workaround
        self.shutdown = False
        
        # Event loop
        self.eventThread = threading.Thread(target=self.__eventLoop)
        self.queue = queue.Queue()
        
        # Event listener
        self.listenerThread = threading.Thread(target=self.__flushEvents)
        self.clipboard = Clipboard()

        self.__initMappings()

        # Set initial lock state
        ledMask = self.localDisplay.get_keyboard_control().led_mask
        mediator.set_modifier_state(Key.CAPSLOCK, (ledMask & CAPSLOCK_LEDMASK) != 0)
        mediator.set_modifier_state(Key.NUMLOCK, (ledMask & NUMLOCK_LEDMASK) != 0)

        # Window name atoms
        self.__NameAtom = self.localDisplay.intern_atom("_NET_WM_NAME", True)
        self.__VisibleNameAtom = self.localDisplay.intern_atom("_NET_WM_VISIBLE_NAME", True)
        
        if not common.USING_QT:
            self.keyMap = Gdk.Keymap.get_default()
            self.keyMap.connect("keys-changed", self.on_keys_changed)
        
        self.__ignoreRemap = False
        
        self.eventThread.start()
        self.listenerThread.start() 
Example #20
Source File: interface.py    From autokey with GNU General Public License v3.0 5 votes vote down vote up
def _restore_clipboard_text(self, backup: str):
        """Restore the clipboard content."""
        # Pasting takes some time, so wait a bit before restoring the content. Otherwise the restore is done before
        # the pasting happens, causing the backup to be pasted instead of the desired clipboard content.
        time.sleep(0.2)
        self.clipboard.text = backup if backup is not None else "" 
Example #21
Source File: interface.py    From autokey with GNU General Public License v3.0 5 votes vote down vote up
def _send_string_selection(self, string: str):
        """Use the mouse selection clipboard to send a string."""
        backup = self.clipboard.selection  # Keep a backup of current content, to restore the original afterwards.
        if backup is None:
            logger.warning("Tried to backup the X PRIMARY selection content, but got None instead of a string.")
        self.clipboard.selection = string
        self.__enqueue(self._paste_using_mouse_button_2)
        self.__enqueue(self._restore_clipboard_selection, backup) 
Example #22
Source File: interface.py    From autokey with GNU General Public License v3.0 5 votes vote down vote up
def _restore_clipboard_selection(self, backup: str):
        """Restore the selection clipboard content."""
        # Pasting takes some time, so wait a bit before restoring the content. Otherwise the restore is done before
        # the pasting happens, causing the backup to be pasted instead of the desired clipboard content.

        # Programmatically pressing the middle mouse button seems VERY slow, so wait rather long.
        # It might be a good idea to make this delay configurable. There might be systems that need even longer.
        time.sleep(1)
        self.clipboard.selection = backup if backup is not None else "" 
Example #23
Source File: scripting.py    From autokey with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, app):
        self.clipBoard = QApplication.clipboard()
        self.app = app 
Example #24
Source File: scripting.py    From autokey with GNU General Public License v3.0 5 votes vote down vote up
def fill_selection(self, contents):
        """
        Copy text into the X selection
        
        Usage: C{clipboard.fill_selection(contents)}
        
        @param contents: string to be placed in the selection
        """
        self.__execAsync(self.__fillSelection, contents) 
Example #25
Source File: scripting.py    From autokey with GNU General Public License v3.0 5 votes vote down vote up
def fill_clipboard(self, contents):
        """
        Copy text into the clipboard
        
        Usage: C{clipboard.fill_clipboard(contents)}
        
        @param contents: string to be placed in the selection
        """
        self.__execAsync(self.__fillClipboard, contents) 
Example #26
Source File: interface.py    From autokey with GNU General Public License v3.0 5 votes vote down vote up
def text(self):
        """Get and set the keyboard clipboard content."""
        return 
Example #27
Source File: scripting.py    From autokey with GNU General Public License v3.0 5 votes vote down vote up
def fill_selection(self, contents):
        """
        Copy text into the X selection
        
        Usage: C{clipboard.fill_selection(contents)}
        
        @param contents: string to be placed in the selection
        """
        #self.__execAsync(self.__fillSelection, contents)
        self.__fillSelection(contents) 
Example #28
Source File: ssh_add.py    From restatic with GNU General Public License v3.0 5 votes vote down vote up
def generate_key_result(self, exitCode, exitStatus):
        if exitCode == 0:
            output_path = os.path.expanduser(self.outputFileTextBox.text())
            pub_key = open(output_path + ".pub").read().strip()
            clipboard = QApplication.clipboard()
            clipboard.setText(pub_key)
            self.errors.setText(
                f"New key was copied to clipboard and written to {output_path}."
            )
        else:
            self.errors.setText("Error during key generation.") 
Example #29
Source File: scripting.py    From autokey with GNU General Public License v3.0 5 votes vote down vote up
def fill_clipboard(self, contents):
        """
        Copy text into the clipboard
        
        Usage: C{clipboard.fill_clipboard(contents)}
        
        @param contents: string to be placed in the selection
        """
        Gdk.threads_enter()
        if Gtk.get_major_version() >= 3:
            self.clipBoard.set_text(contents, -1)
        else:
            self.clipBoard.set_text(contents)
        Gdk.threads_leave() 
Example #30
Source File: main_win.py    From BlindWatermark with GNU General Public License v3.0 5 votes vote down vote up
def checkItem(self,index):

        file_path = (index.data().split('→'))[-1]
        if index.data()[:4]=='使用密钥':
            clipboard = QApplication.clipboard()
            clipboard.setText(file_path) #此处为密钥
        else:
            self.open_pic = open_pic_thread(file_path)
            self.open_pic.finished.connect(self.open_pic.deleteLater)
            self.open_pic.start()
        # QMessageBox.information(self,"ListView",'row:%s, text:%s' % (index.row(), index.data()))