Beispiel #1
0
    def saveScreenshot(self,
                       clipboard=False,
                       fileName='screenshot.png',
                       picType='png'):
        fullWindow = QRect(0, 0, self.width() - 1, self.height() - 1)
        selected = QRect(self.selectedArea)
        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)
        image.setDevicePixelRatio(1)

        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))
Beispiel #2
0
 def setClipboard(self, text):
     """
     Public slot to set some clipboard text.
     
     @param text text to be copied to the clipboard
     @type str
     """
     QGuiApplication.clipboard().setText(text)
Beispiel #3
0
 def copy_result(self):
     """Copies the font command (as shown) to the clipboard."""
     from PyQt5.QtGui import QGuiApplication
     cmd = self.font_cmd()
     if cmd[-1] != '\n':
         cmd = cmd + '\n'
     QGuiApplication.clipboard().setText(cmd)
     self.accept()
Beispiel #4
0
    def next_word(self):
        word = self.dictionary.next_word(
            self.database.marked_indices if self.show_marked_only else None)
        if word:
            self.lineEdit.setText(word['word'])
            # self.display_progress()
            self.highlight_marked(self.database.is_marked(word['idx']))

            QGuiApplication.clipboard().setText(word['word'])
Beispiel #5
0
    def copy(self, selected_region):
        """Copy selected region of pixels to the QGuiApplication clipboard

        :param selected_region: Rectangular region of pixels to copy to
                                clipboard
        :type selected_region:  QRect
        """
        QGuiApplication.clipboard().setImage(
            self.subject.copy(selected_region)
        )
Beispiel #6
0
 def mousePressEvent(self, event):
     if Qt.LeftButton != event.button():
         return
     pos = event.pos()
     clicked = self.childAt(pos)
     if isinstance(clicked, QLabel):
         text = clicked.text()
         QGuiApplication.clipboard().setText(text)
         self.setWindowTitle(text)
     print("ouch")
Beispiel #7
0
    def fromSVG(layerNode, svgContent, document=None):
        """Paste given `svgContent` to `position` in '`layerNode`

        Given `layerNode` must be a 'vectorlayer'

        The `position` value can be:
        - None, in this case, pixmap will be pasted at position (0, 0)
        - A QPoint() object, pixmap will be pasted at defined position

        Note:
        - If document is None, consider that active document contains layer
        - If document is provided, it must contains layerNode

        Method return a list of shapes (shape inserted into layer)
        """
        if isinstance(svgContent, str):
            svgContent=svgContent.encode()

        if not isinstance(svgContent, bytes):
            raise EInvalidType("Given `svgContent` must be a valid <str> or <bytes> SVG document")

        if not isinstance(layerNode, Node) or layerNode.type()!='vectorlayer':
            raise EInvalidType("Given `layerNode` must be a valid <VectorLayer>")

        if document is None:
            document=Krita.instance().activeDocument()

        if not isinstance(document, Document):
            raise EInvalidType("Given `layerNode` must be a valid <Document>")

        shapes=[shape for shape in layerNode.shapes()]

        activeNode=document.activeNode()
        document.setActiveNode(layerNode)
        document.waitForDone()

        # Note: following sleep() is here because waitForDone() doesn't seems to
        #       wait for active node changed...
        #       set an arbitrary sleep() delay allows to ensure that node is active
        #       at the end of method execution
        #       hope current delay is not too short (works for me... but can't put
        #       a too long delay)
        #
        #       Problem occurs with krita 4.4.2 & and tested Krita plus/next tested [2020-01-05]
        EKritaNode.__sleep(100)

        mimeContent=QMimeData()
        mimeContent.setData('image/svg', svgContent)
        mimeContent.setData('BCIGNORE', b'')
        QGuiApplication.clipboard().setMimeData(mimeContent)
        Krita.instance().action('edit_paste').trigger()

        newShapes=[shape for shape in layerNode.shapes() if not shape in shapes]

        return newShapes
Beispiel #8
0
 def on_context_menu(self, point):
     index = self.view.indexAt(point)
     if index.isValid():
         menu = QMenu()
         menu.addAction(
             QIcon(":/images/themes/default/mActionEditCopy.svg"),
             self.tr("Copy resource path to clipboard"),
         )
         menu.exec(self.view.mapToGlobal(point))
         QGuiApplication.clipboard().setText(
             self.proxy_model.data(index, Qt.EditRole))
Beispiel #9
0
 def onClipboardChanged(self, mode):
     if mode == QClipboard.Clipboard:
         if not QGuiApplication.clipboard().ownsClipboard():
             self.clipboardTimer.start()
         else:
             self.clipboardTimer.stop()
     elif mode == QClipboard.Selection:
         if not QGuiApplication.clipboard().ownsSelection():
             self.selectionTimer.start()
         else:
             self.selectionTimer.stop()
 def clipboard_handler(event):
     if event.key == 'ctrl+c':
         # store the image in a buffer using savefig(), this has the
         # advantage of applying all the default savefig parameters
         # such as background color; those would be ignored if you simply
         # grab the canvas using Qt
         buf = io.BytesIO()
         fig.savefig(buf)
         QGuiApplication.clipboard().setImage(
             QImage.fromData(buf.getvalue()))
         buf.close()
Beispiel #11
0
def to(text):
    try:
        from PyQt5.QtGui import QGuiApplication as QApplication

    except ImportError:
        try:
            from PyQt4.QtGui import QApplication

        except ImportError:
            from PySide.QtGui import QApplication

    app = QApplication([])
    app.clipboard().setText(text)
    app = None
Beispiel #12
0
 def copySelection(self):
     selection = self.tabla_combinaciones.selectedIndexes()
     if selection:
         rows = sorted(index.row() for index in selection)
         columns = sorted(index.column() for index in selection)
         rowcount = rows[-1] - rows[0] + 1
         colcount = columns[-1] - columns[0] + 1
         table = [[''] * colcount for _ in range(rowcount)]
         for index in selection:
             row = index.row() - rows[0]
             column = index.column() - columns[0]
             table[row][column] = index.data()
         stream = StringIO()
         writer(stream, delimiter='\t').writerows(table)
         QGuiApplication.clipboard().setText(stream.getvalue())
Beispiel #13
0
    def __init__(self, page=8, row=8, column=8):
        super().__init__()
        self.page = page
        self.row = row
        self.column = column

        self.pt = Pattern()
        self.format = 'dec'

        self.cb = QGuiApplication.clipboard()

        matrixs = self.matrixs(8)

        console = self.console()

        main_layout = QVBoxLayout()
        main_layout.addLayout(matrixs)
        main_layout.addStretch(1)
        main_layout.addLayout(console)

        self.setLayout(main_layout)
        self.center_windows()
        self.setWindowTitle('PatternFlow')
        self.resize(800, 400)
        self.show()
Beispiel #14
0
    def on_copy_to_clipboard(self):
        pixmap = self.web_view.grab()
        clipboard = QGuiApplication.clipboard()

        data = QMimeData()
        data.setImageData(pixmap)
        clipboard.setMimeData(data, QClipboard.Clipboard)
Beispiel #15
0
 def __init__(self, config_dict):
     super().__init__()
     self.config_dict = config_dict
     self.clipboard = QGuiApplication.clipboard()
     self.reconstruct = enable_rhc(config_dict["random_hit_chance"])(
         self.reconstruct)
     self.clipboard.dataChanged.connect(self.reconstruct)
Beispiel #16
0
 def __init__(self, parent=None):
     super().__init__(parent)
     self._p = 0
     self._g = 0
     self._y = 0
     self._source_message = ""
     self._clipboard = QGuiApplication.clipboard()
Beispiel #17
0
 def enterEvent(self, event = None):
     # print("SHOW!")
     clipboard=QGuiApplication.clipboard()
     try:
         self.beforedoit = clipboard.text()
         if self.textbrowser.toPlainText() == self.beforedoit:
             raise ValueError("没什么新内容需要处理")
         if self.beforedoit == '':
             raise ValueError('剪贴板为空')
         self.textbrowser2.setText(self.beforedoit)
         self.beforedoit = self.beforedoit.replace('\n',' ')
         if self.beforedoit == self.textbrowser2.toPlainText():
             # self.info_label4.setText("复制到剪贴板(&C)")
             raise ValueError("没什么需要处理的")
         else:
             self.info_label4.setText("复制到剪贴板(&C)")
             # self.dirty = True
         self.info_label = '处理完毕,更新后的文本已复制到你的剪贴板'
         clipboard.setText(self.beforedoit)
     except:
         self.info_label = '[未检测到内容]请将需要处理的文本复制到剪贴板,然后返回本程序'
         
     self.textbrowser.setText(self.beforedoit)
     # self.textbrowser.selectAll()
     self.setWindowTitle("%s %s - %s"%(__TITLE__,__VERSION__,self.info_label))
Beispiel #18
0
 def __init__(self, config_dict):
     super().__init__()
     self.config_dict = config_dict
     self.clipboard = QGuiApplication.clipboard()
     self.reconstruct = enable_rhc(config_dict["random_hit_chance"])(
         self.reconstruct
     )
     self.clipboard.dataChanged.connect(self.reconstruct)
Beispiel #19
0
 def doitByhand(self):
     try:
         self.textbrowser.setText(self.textbrowser2.toPlainText().replace('\n',' '))
         clipboard=QGuiApplication.clipboard()
         clipboard.setText(self.textbrowser.toPlainText())
         self.info_label4.setText("复制到剪贴板(&C)")
     except:
         traceback.print_exc()
Beispiel #20
0
 def emitChanged(self, mode):
     clipboard = QGuiApplication.clipboard()
     mimeData = clipboard.mimeData()
     data = {}
     for format in self.formats:
         if mimeData.hasFormat(format):
             data[format] = mimeData.data(format)
     self.changed.emit(data)
Beispiel #21
0
 def copy(self):
     if not self.bill.isEnabled():
         return
     text = self.bill.toPlainText()
     if text == "":
         return
     clipboard = QGuiApplication.clipboard()
     clipboard.setText(text)
Beispiel #22
0
    def __init__(self, engine):
        super(ScreenShot, self).__init__()
        self.provider = ScreenShotProvider()
        self.clipboard = QGuiApplication.clipboard()
        self.clipboard.dataChanged.connect(self.on_changed)

        engine.addImageProvider("screenshot", self.provider)
        engine.rootContext().setContextProperty("screenshot", self)
Beispiel #23
0
 def copy(self):
     if not self.generated_text_area.isEnabled():
         return
     text = self.generated_text_area.toPlainText()
     if text == "":
         return
     clipboard = QGuiApplication.clipboard()
     clipboard.setText(text)
 def copyPushButtonClicked(self):
     #setting clipboard contents to thumb if it exists
     if (self.imageUrl != None):
         clipboard = QGuiApplication.clipboard()
         data = QMimeData()
         data.setImageData(self.thumbnailImage)
         clipboard.setMimeData(data)
         self.statusbar.showMessage("Thumbnail copied", 4000)
     else:
         self.statusbar.showMessage("No thumbnail to copy", 4000)
Beispiel #25
0
 def paste(self):
     """Entry point for pasting a pixel region after a selection is copied
     """
     self.selecting = False
     self.pasting = True
     self.select_timer.stop()
     self.scene.update()
     self.copied = QGuiApplication.clipboard().image()
     self.scene.region_selected.emit(False)
     self.renderPaste(self.last_pos)
Beispiel #26
0
    def __init__(self):
        super(BaiduDiskToolWidget, self).__init__()
        self.mywidgetui = baidudisktool_ui.Ui_MainWindow()
        self.mywidgetui.setupUi(self)
        self.mywidgetui.pushButtonBaiduOpen.clicked.connect(
            self.__slotOpenUrl)  # 信号与槽连接
        self.mywidgetui.pushButtonBaiduCopy.clicked.connect(
            self.__slotCopyUrl)  # 信号与槽连接

        self.board = QGuiApplication.clipboard()
Beispiel #27
0
    def copy_dates_to_clipboard(self):
        """Функция слот нажатия на кнопку копирования задач (без даты и времени)"""
        result = [task['dt_string'] for task in self.loaded_tasks]

        if not result:
            dialog = InfoDialog(self, 'Ошибка', 'Задачи отсутствуют')
            return dialog.exec_()
        cb = QGuiApplication.clipboard()
        cb.setText('\n'.join(result), mode=cb.Clipboard)
        dialog = InfoDialog(self, 'Успех', 'Даты скопированы в буфер обмена')
        dialog.exec_()
Beispiel #28
0
def paste_name(primary: bool = True) -> None:
    """Paste path from clipboard to open command.

    **syntax:** ``:paste-name [--primary]``

    optional arguments:
        * ``--primary``: Paste from  primary selection.
    """
    clipboard = QGuiApplication.clipboard()
    mode = QClipboard.Selection if primary else QClipboard.Clipboard
    api.open_paths([clipboard.text(mode=mode)])
Beispiel #29
0
  def copy(self):
    clipboard = QGuiApplication.clipboard()
    rect = self.scene.sceneRect() if self.view.selection() == QRect() else self.view.sceneSelection()
    board = QImage(rect.size().toSize(), QImage.Format_ARGB32)
    board.fill(Qt.transparent)
    painter = QPainter(board)
    self.scene.render(painter, QRectF(), rect)
    board1 = board.scaled(board.width()*2, board.height()*2)

    clipboard.setImage(board1)
    painter.end()
    self.statusBar().showMessage('Copied!', 500)
Beispiel #30
0
    def copy_data_to_clipboard(self):
        clipboard = QGuiApplication.clipboard()

        output = ''
        for row in range(self.UI.tableData.rowCount()):
            for col in range(self.UI.tableData.columnCount()):
                output += self.UI.tableData.item(row, col).text()
                if col < self.UI.tableData.columnCount() - 1:
                    output += '\t'
            if row < self.UI.tableData.rowCount() - 1:
                output += '\n'
        clipboard.setText(output)
Beispiel #31
0
def copy_image(
    primary: bool = False,
    width: int = None,
    height: int = None,
    size: int = None,
    count: int = None,
) -> None:
    """Copy currently selected image to system clipboard.

    **syntax:** ``:copy-image [--primary] [--width=WIDTH] [--height=HEIGHT]
    [--size=SIZE]``

    optional arguments:
        * ``--primary``: Copy to primary selection.
        * ``--width``: Scale width to the specified value.
        * ``--height``: Scale height to the specified value.
        * ``--size``: Scale longer side to the specified value.

    **count:** Equivalent to the ``--size`` option
    """
    clipboard = QGuiApplication.clipboard()
    mode = QClipboard.Selection if primary else QClipboard.Clipboard
    path = api.current_path()

    try:
        reader = imagereader.get_reader(path)
        pixmap = reader.get_pixmap()
    except ValueError as e:
        log.error(str(e))
        return

    if size or count:
        pix_size = pixmap.size()

        size = count if count is not None else size

        if pix_size.height() >= pix_size.width():
            _logger.debug(f"Copy image with size {size} restricting height")
            pixmap = pixmap.scaledToHeight(size)  # type: ignore[arg-type]
        else:
            _logger.debug(f"Copy image with size {size} restricting width")
            pixmap = pixmap.scaledToWidth(size)  # type: ignore[arg-type]

    elif width:
        _logger.debug(f"Copy image with width {width}")
        pixmap = pixmap.scaledToWidth(width)

    elif height:
        _logger.debug(f"Copy image with height {height}")
        pixmap = pixmap.scaledToHeight(height)

    clipboard.setPixmap(pixmap, mode=mode)
Beispiel #32
0
def copy_name(abspath: bool = False, primary: bool = False) -> None:
    """Copy name of current path to system clipboard.

    **syntax:** ``:copy-name [--abspath] [--primary]``

    optional arguments:
        * ``--abspath``: Copy absolute path instead of basename.
        * ``--primary``: Copy to primary selection.
    """
    clipboard = QGuiApplication.clipboard()
    mode = QClipboard.Selection if primary else QClipboard.Clipboard
    path = api.current_path()
    name = path if abspath else os.path.basename(path)
    clipboard.setText(name, mode=mode)
Beispiel #33
0
    def enterEvent(self, event=None):
        # print("SHOW!")
        clipboard = QGuiApplication.clipboard()
        try:
            self.beforedoit = clipboard.text()
            self.beforedoit = self.beforedoit.replace('\n', ' ')
            self.info_label = '处理完毕,更新后的文本已复制到你的剪贴板'
            clipboard.setText(self.beforedoit)
        except:
            self.info_label = '[未检测到内容]请将需要处理的文本复制到剪贴板'

        self.textbrowser.setText(self.beforedoit)
        self.setWindowTitle("%s %s - %s" %
                            (__TITLE__, __VERSION__, self.info_label))
Beispiel #34
0
    def __init__(self):
        QObject.__init__(self)
        clipboard = QGuiApplication.clipboard()
        clipboard.changed.connect(self.onClipboardChanged)

        self.clipboardTimer = QTimer()
        self.clipboardTimer.setInterval(500)
        self.clipboardTimer.setSingleShot(True)
        self.clipboardTimer.timeout.connect(self.onClipboardChangedAfterDelay)

        self.selectionTimer = QTimer()
        self.selectionTimer.setInterval(1000)
        self.selectionTimer.setSingleShot(True)
        self.selectionTimer.timeout.connect(self.onSelectionChangedAfterDelay)

        self.formats = set([mimeText])
Beispiel #35
0
    def __init__(self, parent = None):
        super().__init__(parent)
        self.app = QGuiApplication.instance()
        self._queue = deque()
        self.frontendpy = parent

        self._listener = threading.Thread(target = self.listenerThread, daemon = True,
                                          name = "frontend communication listener")
        self._listener.start()

        tasks = sys.argv[1:]
        if tasks:
            self.createTasksAction(tasks)

        self.urlExtractor = UrlExtractor(self)

        self._clipboard = QGuiApplication.clipboard()
        self.app.settings.applySettings.connect(self.slotWatchClipboardToggled)
Beispiel #36
0
 def text(self):
     clipboard = QGuiApplication.clipboard()
     return clipboard.text()
        myObj = obj.findChild(QObject, "loginHandle")
        QMetaObject.invokeMethod(myObj, "loginResult", Qt.QueuedConnection, Q_ARG(QVariant, string))

    @pyqtSlot(str, str)
    def login(self, email, password):
        self.cw.authenticate(email, password)

    @pyqtSlot()
    def stop(self):
        self.cw.stop()
        sys.exit()


if __name__ == "__main__":
    app = QGuiApplication(sys.argv)
    clipboard = app.clipboard()

    # add icon
    app_icon = QIcon()
    app_icon.addFile(path.join("qml", "img", "logo.jpg"))
    app.setWindowIcon(app_icon)

    engine = QQmlApplicationEngine()
    ctx = engine.rootContext()
    py = QMLNameSpace(engine, clipboard)
    ctx.setContextProperty("main", engine)
    ctx.setContextProperty("py", py)

    # engine.addImportPath(path.join(getcwd(), 'qml'))
    engine.setImportPathList([path.join(getcwd(), "qml", "lib")])
Beispiel #38
0
 def copyText(self, text):
     from PyQt5.QtGui import QGuiApplication
     clip = QGuiApplication.clipboard()
     clip.setText(text)
    return getSelectedTextFunc(desktop)

lock = threading.Lock()

def textCopied():
    with lock:
        print("copiedText:" + getSelectedText());
        sys.stdout.flush();

def selectingText():
    previousSelectedText = None;
    currentSelectedText = None;
    while True:
        currentSelectedText = getSelectedText();
        if currentSelectedText and currentSelectedText != previousSelectedText:
            with lock:
                print("selectedText:" + currentSelectedText);
                sys.stdout.flush();
            previousSelectedText = currentSelectedText;

        time.sleep(0.05);

t = threading.Thread(target=selectingText);
t.daemon = True;
t.start();

app = QGuiApplication(sys.argv);
clipboard = QGuiApplication.clipboard()
clipboard.dataChanged.connect(textCopied)
sys.exit(app.exec_())
Beispiel #40
0
 def text(self, text):
     clipboard = QGuiApplication.clipboard()
     return clipboard.setText(text)