gpt4 book ai didi

c++ - 使用 Qthread-Qt5 创建新线程

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:28:49 24 4
gpt4 key购买 nike

我正在尝试创建一个新线程 gpsthread,它应该在后台运行并存储值。

class gpsthread: public QThread{
Q_OBJECT
private:nrega_status_t status2;

public:
explicit gpsthread(QObject *parent = 0):QThread(parent) {
// QTimer *t = new QTimer(this);
// connect(t, SIGNAL(timeout()), this, SLOT(processgps()));
// t->start(10000);
}
void run(){
qDebug()<<"inside gps thread\n";
QTimer *t = new QTimer(this);
connect(t, SIGNAL(timeout()), this, SLOT(processgps()));
t->start(10000);
}

public slots:void processgps(){
int status2;
status2=gps_management();
}
};

我的主类是quickview。

int main(int argc, char *argv[])
{

QString file = "qml/main.qml";
QApplication app(argc, argv);
TranslationTest myObj;
QuickView view;
subthread object;
gpsthread obj;
gprsthread gprs;
view.rootContext()->setContextProperty("rootItem", (QObject *)&myObj);

obj.start();
//from subthread
QObject::connect(&object, SIGNAL(batterytoqml(QVariant,QVariant)),item, SLOT(frombattery(QVariant,QVariant)));
QObject::connect(&gprs, SIGNAL(gprstoqml(QVariant)),item, SLOT(fromgprs(QVariant)));
return app.exec();

我也试过

class gpsthread: public QThread{
Q_OBJECT
private:nrega_status_t status2;

public:QTimer* t;
explicit gpsthread(QObject *parent = 0):QThread(parent) {
// QTimer *t = new QTimer(this);
// connect(t, SIGNAL(timeout()), this, SLOT(processgps()));
// t->start(10000);
}
void run(){
qDebug()<<"inside gps thread\n";
t = new QTimer(this);
connect(t, SIGNAL(timeout()), this, SLOT(processgps()));
t->start(10000);
exec();
}

public slots:void processgps(){
int status2;
status2=gps_management();
}
};

但是报错

 QObject: Cannot create children for a parent that is in a different thread

如果我在构造函数中创建对象,那么它也会给出相同的错误,因为该对象将在主线程中创建。如何解决这个问题?

最佳答案

从 QThread 继承不是推荐的用法。 QThread 是一个运行事件循环的完整类,这通常是您需要的。 documentation建议使用继承自 QObject 并在插槽中工作的工作对象。 worker 被移动到 QThread 中。发送连接信号时,插槽将在正确的线程中运行。

class gpsworker: public QObject
{
Q_OBJECT
public:
explicit gpsworker(QObject *parent = 0):
QObject(parent)
{}

public slots:
void processgps() {
qDebug() << "processgps()" << QThread::currentThreadId();
}
}

void OwnerClass::startWorker() {
QTimer *timer = new QTimer(this);
QThread *thread = new QThread(this);
this->worker = new gpsworker();
this->worker->moveToThread(thread);
connect(timer, SIGNAL(timeout()), this->worker, SLOT(processgps()) );
connect(thread, SIGNAL(finished()), this->worker, SLOT(deleteLater()) );
thread->start();
timer->start();
}

如果您希望计时器也存在于其他线程中,QTimer::start 是一个插槽。

关于c++ - 使用 Qthread-Qt5 创建新线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24776697/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com