Hi everyone,
I have one GUI class, one thread class, and one timer inside thread class.
mainwindow.h file:
{
Q_OBJECT
public:
testClass();
void run();
public slots:
void timerExpired();
void startWork();
private:
};
{
Q_OBJECT
public:
explicit MainWindow
(QWidget *parent
= 0);
~MainWindow();
signals:
void startSignal();
private slots:
void on_pushButton_clicked();
private:
Ui::MainWindow *ui;
};
class testClass : public QThread
{
Q_OBJECT
public:
testClass();
void run();
public slots:
void timerExpired();
void startWork();
private:
QTimer *timer;
};
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
signals:
void startSignal();
private slots:
void on_pushButton_clicked();
private:
Ui::MainWindow *ui;
};
To copy to clipboard, switch view to plain text mode
mainwindow.c
void MainWindow::on_pushButton_clicked()
{
emit startSignal();
}
testClass::testClass()
{}
void testClass::run()
{
QObject::connect(timer,
SIGNAL(timeout
()),
this,
SLOT(timerExpired
()),Qt
::DirectConnection);
exec();
}
void testClass::startWork()
{
timer->start(0);
}
void testClass::timerExpired()
{
qDebug("Timer expired.");
}
void MainWindow::on_pushButton_clicked()
{
emit startSignal();
}
testClass::testClass()
{}
void testClass::run()
{
timer = new QTimer();
QObject::connect(timer,SIGNAL(timeout()),this,SLOT(timerExpired()),Qt::DirectConnection);
exec();
}
void testClass::startWork()
{
timer->start(0);
}
void testClass::timerExpired()
{
qDebug("Timer expired.");
}
To copy to clipboard, switch view to plain text mode
main.cpp
int main(int argc, char *argv[])
{
MainWindow w;
testClass tCls;
QObject::connect(&w,
SIGNAL(startSignal
()),
&tCls,
SLOT(startWork
()),Qt
::QueuedConnection);
w.show();
tCls.
start(QThread::NormalPriority);
return a.exec();
}
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
testClass tCls;
QObject::connect(&w,SIGNAL(startSignal()),&tCls,SLOT(startWork()),Qt::QueuedConnection);
w.show();
tCls.start(QThread::NormalPriority);
return a.exec();
}
To copy to clipboard, switch view to plain text mode
In this case I am getting a run time error "QObject::startTimer: timers cannot be started from another thread".
What I understood :
timer is allocated inside run() so it belogs to testClass thread.But when i was trying to call the testClass::startWork() slot from mainwindow at that time testClass::startWork() belongs to mainwindow thread. So the timer is not able to start.
If I will take timer as static(from stack) then it will be fine because timer will be in main thread.
What i have mentioned here is it true ?
Is the member function of testClass belongs to testClass thread or not ?
I am using signal slot to communicate between two thread .But the current thread id of mainwindow and startWork() slot are same.
How i solve this ?
thanks.
Bookmarks