1

I have the follow constellation:

A qt gui thread with MainWindow

Another thread which essentially is a CameraManager...everytime a camera is added/removed the MainWindow will be informed.

It roughly looks like this:

Mainwindow derives from ICameraAddedConsumer

MainWindow implements ConsumeCameraAdded and creates widget inside this function. It subscribes itselv as a consumer to the CameraManager

CameraManager calls ConsumeCameraAdded of all it's consumers (MainWindow) when a new camera is added.

The problem is that CameraManager lives in a different thread and Qt will obviously complain about this since a widget is not created in the same thread as the mainwindow was.

Any suggestions how I can solve this?

5
  • 2
    I'd expect signals and slots to take care of that inter-thread communication. You don't subscribe to the manager but you connect one of its signals to one of your slots. Commented Mar 4, 2019 at 9:19
  • doc.qt.io/archives/qt-4.8/… Commented Mar 4, 2019 at 9:29
  • I thought about that, but what if I dont want the CameraManager to be a Q_OBJECT? Commented Mar 4, 2019 at 9:31
  • ...you just wrap it in an adapter that is a Q_OBJECT. Commented Mar 4, 2019 at 10:05
  • Or, you can use Boost signals. It is very useful when you don't want to use QObject in you business logic. Commented Mar 4, 2019 at 10:07

1 Answer 1

1

As per comments, using signals/slots between QObjects in different threads should take care of the issue "automagically."

Barring that, and assuming MainWindow/ICameraAddedConsumer is a QObject, one idea could be to use something like:

QMetaObject::invokeMethod(consumer, "ConsumeCameraAdded", Qt::QueuedConnection, ...)

where consumer is a pointer to the MainWindow/ICameraAddedConsumer instance.

There's QWaitCondition but I'm not sure that makes sense in this case (though it could be adapted I suppose).

Otherwise... don't create the widget in ConsumeCameraAdded() but set some flag there (and return) and then use a QTimer or QObject::timerEvent() to periodically check the flag and create widget if it is set. Unfortunately I'm pretty sure you will not be able to create or start a timer within ConsumeCameraAdded() itself because of threading issues.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.