Reputation: 371
I have the following classes:
class MainWindow : public QMainWindow
{
public:
void StartTimer()
{
timer = new QTimer(this);
timer.start(100);
}
private:
QTimer *timer;
};
class AnotherClass
{
public:
MainWindow *window;
void runTimer()
{
window->StartTimer();
}
};
Assuming the window pointer is correctly pointing to the mainwindow, if I try to call runTimer()
, I receive this error:
QObject: Cannot create children for a parent that is in a different thread.
(Parent is MainWindow(0x7fff51ffe9f0), parent's thread is QThread(0x7fd1c8d001d0), current thread is QThread(0x7fd1c8f870c0)
QObject::startTimer: Timers can only be used with threads started with QThread
My guess for this error was that since runTimer was being called from a different thread it was also trying to initialize in that same thread? instead of the mainwindow thread?
If I initialize the timer in the default constructor of the main window I receive
QObject::startTimer: Timers cannot be started from another thread
How can I tell a QTimer to start from another class?
Upvotes: 0
Views: 975
Reputation: 2708
You can use signals and slots.
class AnotherClass : public QObject
{
Q_OBJECT
public:
MainWindow * window;
AnotherClass() : window( new MainWindow )
{
// Connect signal to slot (or just normal function, in this case )
connect( this, &AnotherClass::signalStartTimer,
window, &MainWindow::StartTimer,
// This ensures thread safety, usually the default behavior, but it doesn't hurt to be explicit
Qt::QueuedConnection );
runTimer();
}
void runTimer()
{
emit signalStartTimer();
}
signals:
void signalStartTimer();
};
Upvotes: 1