0

hi i have class with function that run according to QTimer (run every 30ms for example )

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).

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 ?

user2612344
  • 77
  • 1
  • 6

2 Answers2

4

I recommend to use QtConcurrent. It is a lot of less headache then using directly 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.

Marek R
  • 32,568
  • 6
  • 55
  • 140
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();
}

regarding comments, you can also subclass QThread directly this way:

class MyThreadedClass : public QThread
{
  MyThreadClass(){}

  void doSomething(){
      }

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

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

  return 0;
}
4pie0
  • 29,204
  • 9
  • 82
  • 118