Accessing QtGui.QApplication.clipboard from the run method of QtCore.QThread

James Crosswell

I have the following simple clipboard watcher thread/class:

import time
from PyQt4 import QtGui, QtCore


class ClipboardWatcher(QtCore.QThread):

    clip_detected = QtCore.pyqtSignal(object)

    def __init__(self):
    QtCore.QThread.__init__(self)
    self._pause = 5.

    def __del__(self):
    self.wait()

    def run(self):       
    recent_value = ""
    #clipboard = QtGui.QApplication.clipboard()

    while True:
        self.clip_detected.emit("Testing 123...")
        tmp_value = ""
        #tmp_value = clipboard.text()
        if tmp_value != recent_value:
            recent_value = tmp_value
            self.clip_detected.emit(recent_value)
        time.sleep(self._pause)

    self.terminate()

This works fine... The main widget in my PyQt application receives the signal just fine. However if I uncomment the line #clipboard = QtGui.QApplication.clipboard() then I get the following error:

[xcb] Unknown request in queue while dequeuing
[xcb] Most likely this is a multi-threaded client and XInitThreads has not been called
[xcb] Aborting, sorry about that.
python2.7: ../../src/xcb_io.c:179: dequeue_pending_request: Assertion `!xcb_xlib_unknown_req_in_deq' failed.

I'm a python newbie (this is my first app) so not too sure what I'm doing wrong here...

three_pineapples

I suspect the error is because the QClipboard is not thread safe. The Qt documentation doesn't explictly say this, but it does say (ref):

Lastly, the X11 clipboard is event driven, i.e. the clipboard will not function properly if the event loop is not running. Similarly, it is recommended that the contents of the clipboard are stored or retrieved in direct response to user-input events, e.g. mouse button or key presses and releases. You should not store or retrieve the clipboard contents in response to timer or non-user-input events.

As such, I suspect you should not be reading the clipboard from a QThread. I would suggest coming up with another solution to your problem.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related