Get the selected text content from other programs

2019-09-19 13:29发布

When I am using other programs (e.g. opening a pdf or word), I will select some text contents (like a word or paragraph) by using the mouse. I want my python program to get this text content. How to do this using PyQt, or some other Python library?

1条回答
三岁会撩人
2楼-- · 2019-09-19 13:46

This is an easy task, you haven't specified the pyqt version, so I'll post the solution for PyQt4, here you go:

from PyQt4.QtCore import QObject, pyqtSlot, SIGNAL, SLOT
from PyQt4.QtGui import QApplication, QMessageBox
import sys


class MyClipboard(QObject):

    @pyqtSlot()
    def changedSlot(self):
        if(QApplication.clipboard().mimeData().hasText()):
            QMessageBox.information(None, "Text has been copied somewhere!",
                                    QApplication.clipboard().text())


def main():
    app = QApplication(sys.argv)
    listener = MyClipboard()

    app.setQuitOnLastWindowClosed(False)
    QObject.connect(QApplication.clipboard(), SIGNAL(
        "dataChanged()"), listener, SLOT("changedSlot()"))

    sys.exit(app.exec_())

if __name__ == '__main__':
    main()
查看更多
登录 后发表回答