4
votes

Im trying to send a signal from a non-main thread in PyQt but i dont know what am doing wrong! And when i execute the program it fails with this error:

QObject::connect: Cannot queue arguments of type 'QTextCursor'
(Make sure 'QTextCursor' is registered using qRegisterMetaType().)

here is my code:

 class Sender(QtCore.QThread):
        def __init__(self,q):
            super(Sender,self).__init__()
            self.q=q
        def run(self):

            while True:
                pass
                try: line = q.get_nowait()
             # or q.get(timeout=.1)
                except Empty: 
                    pass
                else: 
                   self.emit(QtCore.SIGNAL('tri()')) 
 class Workspace(QMainWindow, Ui_MainWindow):
    """ This class is for managing the whole GUI `Workspace'.
        Currently a Workspace is similar to a MainWindow
    """

    def __init__(self):  
try:
            from Queue import Queue, Empty
        except ImportError:
            while True:
    #from queue import Queue, Empty  # python 3.x
                print "error"

        ON_POSIX = 'posix' in sys.builtin_module_names

        def enqueue_output(out, queue):
            for line in iter(out.readline, b''):
                queue.put(line)
            out.close()

        p= Popen(["java -Xmx256m -jar bin/HelloWorld.jar"],cwd=r'/home/karen/sphinx4-1.0beta5-src/sphinx4-1.0beta5/',stdout=PIPE, shell=True, bufsize= 4024)
        q = Queue()
        t = threading.Thread(target=enqueue_output, args=(p.stdout, q)) 
          t.daemon = True # thread dies with the program
        t.start()
        self.sender= Sender(q)
         self.connect(self.sender, QtCore.SIGNAL('tri()'), self.__action_About)
        self.sender.start()

I think that my way of send parameter to the thread is wrong... I need to know how to send parameters to a thread, in my case i need to send q to the worker thread.

2
You've already asked this question, and you still haven't provided any code which actually uses QTextCursor. - Dan Milburn
It is likely that the asker was not actually directly using QTextCursor, but rather using GUI code from a thread that was not the GUI thread. Attempting this seems to result in this error arising from Qt-internal code, e.g. for QTextEdit.append(). See: stackoverflow.com/questions/2104779/… - svk
@svk This truly is the correct answer, I think. I suggest you create an answer here. Flag me when you do that, such that I can vote for your answer. - macetw

2 Answers

1
votes

Make sure 'QTextCursor' is registered using qRegisterMetaType().

Did you try to use qRegisterMetaType function?

The official manual says:

The class is used as a helper to marshall types in QVariant and in queued signals and slots connections. It associates a type name to a type so that it can be created and destructed dynamically at run-time. Declare new types with Q_DECLARE_METATYPE() to make them available to QVariant and other template-based functions. Call qRegisterMetaType() to make type available to non-template based functions, such as the queued signal and slot connections.

0
votes

Quite new to PyQt5, but this appears to happen when you try to do a GUI operation from a thread which is not the "application thread". I put this in quotes because it appears to be a mistake to think that, even in a fairly simple PyQt5 app, QApplication.instance().thread() will always return the same object.

The thing to do is to use the signal/slot mechanism to send any kind of data from a worker thread (a thread created in my case by extending QtCore.QRunnable, although there may be other patterns).

Then also include a check in all your slot methods which are likely to receive data from a non-"application thread". Example which logs messages visually during execution:

def append_message(self, message):
    # this "instance" method is very useful!
    app_thread = QtWidgets.QApplication.instance().thread()
    curr_thread = QtCore.QThread.currentThread()
    if app_thread != curr_thread:
        raise Exception('attempt to call MainWindow.append_message from non-app thread')
    ms_now = datetime.datetime.now().isoformat(sep=' ', timespec='milliseconds')
    self.messages_text_box.insertPlainText(f'{ms_now}: {message}\n')
    # scroll to bottom
    self.messages_text_box.moveCursor(QtGui.QTextCursor.End)

It's all too easy to just call this inadvertently and directly from a non-"application thread".

Making such a mistake then raise an exception is good, because it gives you a stack trace showing the culprit call. Then change the call so that it instead sends a signal to the GUI class, the slot for which could be the method in the GUI class (here append_message), or alternatively one which then in turn calls append_message.

In my example I've included the "scroll to bottom" line above because it was only when I added that line that these "cannot queue" errors started happening. In other words, it is perfectly possible to get away with a certain amount of non-compliant handling (in this case adding some more text with each call) without any error being raised... and only later do you then run into difficulties. To prevent this, I suggest that EVERY method in a GUI class with GUI functionality should include such a check!