Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting Table Items Across Multiple Threads

I'm trying to update the values in a table using a separate worker thread, using POSIX threads.

The function the worker thread is executing is trying to do the following:

ui->table->setItem(0,0,new QTableWidgetItem(tr("%1").arg(value)));

However, at runtime I get the following error:

QObject::connect: Cannot queue arguments of type 'QVector<int>'
(Make sure 'QVector<int>' is registered using qRegisterMetaType().)

I'm not quite sure how that qRegisterMetaType works. I'm wondering if anyone has any idea how I can grant the worker thread direct access to the widgets?

like image 944
sj755 Avatar asked Jun 25 '13 15:06

sj755


1 Answers

Accessing any widget from anything but the main thread is not allowed in Qt. All UI operations need to be done from within the main thread (with a few exceptions, such as painting on a QImage).

In your case, emit a signal in the worker thread when you want to add a new item. In the main thread, have a slot that actually creates the item, i.e. calls ui->table->setItem(0,0,new QTableWidgetItem(tr("%1").arg(value)));. Then simply connect() the signal and the slot together. Qt will realize that sender and receiver live in different threads and use a QueuedConnection automatically. You slot will be called whenever Qt's main thread returns to the event loop.

If your signal has parameters, their type needs to be registered with qRegisterMetaType.

like image 87
Thomas McGuire Avatar answered Sep 28 '22 11:09

Thomas McGuire