[英]Using QThread and QTimer to run a methode
hi i have class with function that run according to QTimer
(run every 30ms for example ) 嗨,我有根据
QTimer
运行的函数类(例如,每30ms运行一次)
class testclass
{
public slots:
void DoSomthing();
}
testclass::testclass()
{
QTimer *timer = new QTimer();
connect(timer , SIGNAL(timeout()) , this , SLOT(DoSomthing());
timer->start(30);
}
but i want my DoSomthing()
function to run in separate thread , that's mean make DoSomthing()
function in separate thread and control the function using timer (run my function in thread every some time). 但是我希望我的
DoSomthing()
函数在单独的线程中运行,这意味着使DoSomthing()
在单独的线程中运行,并使用计时器控制该函数(每隔一段时间在线程中运行我的函数)。
class testclass
{
public slots:
void DoSomthing();
}
testclass::testclass()
{
QThread thread = new QThread ();
connect(thread , SIGNAL(started()) , this , SLOT(DoSomthing());
QTimer *timer = new QTimer();
connect(???, SIGNAL(?????) , ????, SLOT(?????); // how i can continue this code
timer->start(30);
}
how i can do it ? 我该怎么办?
I recommend to use QtConcurrent. 我建议使用QtConcurrent。 It is a lot of less headache then using directly QThread.
与直接使用QThread相比,可以减轻很多麻烦。
#include <QtConcurrent/QtConcurrent>
void SomeClass::timerSlot() {
QtConcurrent::run(this, &SomeClass::SomePrivateMethodToRunInThread);
}
void SomeClass::SomePrivateMethodToRunInThread() {
doSomething();
emit someSlot();
}
emitting a signal is thread safe if you are passing only a by values (or const reference) and connecting it using Qt::AutoConnection
(default value) or Qt::QueuedConnection
. 如果仅传递一个by值(或const引用)并使用
Qt::AutoConnection
(默认值)或Qt::QueuedConnection
连接,则发出信号是线程安全的。
class TestClass : public QObject
{
Q_OBJECT
public Q_SLOTS:
void doSomething();
};
int main(int argv, char** args)
{
QApplication app(argv, args);
QTimer *timer = new QTimer();
// Thread
TestClass test;
QThread t;
test.moveToThread(&t);
t.start();
// Connections
QObject::connect(timer, SIGNAL(timeout()), &test, SLOT(doSomething()));
return app.exec();
}
regarding comments, you can also subclass QThread directly this way: 关于注释,您还可以通过以下方式直接子类化QThread:
class MyThreadedClass : public QThread
{
MyThreadClass(){}
void doSomething(){
}
void run()
{
doSomething();
}
};
int main()
{
MyThreadClass thread();
thread.start(); // MyThreadClass is now running
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.