0

嗨,我有一个具有运行功能的类QTimer(例如每 30 毫秒运行一次)

class testclass
{
    public slots:
    void   DoSomthing();

}

testclass::testclass()
{
    QTimer *timer = new QTimer();
    connect(timer , SIGNAL(timeout()) , this , SLOT(DoSomthing());
    timer->start(30);

}

但我希望我的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);
}

我该怎么做?

4

2 回答 2

4

我推荐使用 QtConcurrent。与直接使用 QThread 相比,它的头痛要少得多。

#include <QtConcurrent/QtConcurrent>

void SomeClass::timerSlot() {
    QtConcurrent::run(this, &SomeClass::SomePrivateMethodToRunInThread);
}

void SomeClass::SomePrivateMethodToRunInThread() {
    doSomething();
    emit someSlot();
}

如果您仅传递 a 值(或 const 引用)并使用Qt::AutoConnection(默认值)或Qt::QueuedConnection.

于 2013-07-23T22:32:46.633 回答
0
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();
}

关于评论,你也可以通过这种方式直接继承 QThread:

class MyThreadedClass : public QThread
{
  MyThreadClass(){}

  void doSomething(){
      }

  void run()
  {
    doSomething();
  }
};

int main()
{
  MyThreadClass thread();
  thread.start(); // MyThreadClass is now running

  return 0;
}
于 2013-07-23T22:15:25.807 回答