user3114019
user3114019

Reputation: 21

How to send signals to a qt class from a not qt class?

I created a qt class only to make gui and displayed the data on gui.

i didn't want to freeze the gui that's why i created another non_qt class to perform the operation so i made a object in the gui class of non_qt class and pass the parameter in that and started it in a new thread.

now after completing the operation i want to notify the gui class so it can display the results.

i also want to access the status bar of gui class so when non_qt class is performing the operation it can display some message on gui..

(i tried it with qt class but it didn't work that's why i created non_qt class..with non_qt class threading part is working fine but signal part is not working so i'm not able to notify the gui class).

so please help me out how to send signal to a qt class from a not qt class????

Upvotes: 2

Views: 2229

Answers (1)

The signal is a concept that only applies to classes that derive from QObject.

If you want to trigger a slot, you don't need a signal. If the receiving object lives in the same thread (and only then), you can call the slot method on the reciving object directly.

For example, given an instance of a GUI object with a slot:

MainWindow * mainWindow;

class MainWindow : public QWidget {
  Q_OBJECT
  ...
  Q_SLOT void setStatus(const QString &);
  ...
};

You can simply do:

// The assert is essential to prevent bad bugs. If it triggers,
// you must use `QMetaObject::invokeMethod` instead.
Q_ASSERT(mainWindow->thread() == QThread::currentThread());
mainWindow->setStatus("Finished");

If the receiving object may live in another thread, or if you don't want to worry about threading issues, then you must use QMetaObject::invokeMethod, as follows:

// This is always safe. No need for asserts.
QMetaObject::invokeMethod(mainWindow, "setStatus",
                          Q_ARG(QString, "Finished"));

This overload of invokeMethod will correctly choose the connection type depending on whether the receiving object runs in the same thread. If the receiver is in the same thread, the call is a direct call. If it runs in another thread, the call will be converted to a QMetaCallEvent and posted to the receving object. This is thread-safe and doesn't require the receving object's setStatus method to be thread-safe.

Upvotes: 3

Related Questions