Search code examples
pyqt5pyqt4signals-slots

PyQt5 Get the selected text content from other programs


I was looking at this example from PyQt4.

Get the selected text

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()

However the signal and slots changed in PyQt5, and SIGNAL and SLOT is depreciated. Any suggestion of transforming the PyQt4 SIGNAL and SLOT line.

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

to PyQt5


Solution

  • The equivalent code is:

       QApplication.clipboard().dataChanged.connect(listener.changedSlot)
    

    This is the new-style signal and slot syntax, which has completely replaced the old-style syntax. The old-style syntax is error-prone, verbose, and is not pythonic - in particular, it does not raise an error if you get the signal signature wrong. PyQt4 still supports both syntaxes, but PyQt5 does not support it at all (and never will).