使用Qthread-Qt5创建新线程

问题描述 投票:4回答:2

我正在尝试创建一个新线程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();
}
};

我的主要课程是快速浏览。

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

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

我正在尝试创建一个新线程gpsthread,该线程应在后台运行并存储值。 gpsthread类:公共QThread {Q_OBJECT私有:nrega_status_t status2; public:显式...

c++ multithreading qt5 qthread
2个回答
6
投票

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


1
投票
QObject: Cannot create children for a parent that is in a different thready
© www.soinside.com 2019 - 2024. All rights reserved.