2016-05-14 66 views
0

我有以下類別:從另一個類啓動QTimer

class MainWindow : public QMainWindow 
{ 

public: 
void StartTimer() 
{ 
    timer = new QTimer(this); 
    timer.start(100); 

} 

private: 
QTimer *timer; 

}; 


class AnotherClass 
{ 

public: 
MainWindow *window; 
void runTimer() 
{ 
    window->StartTimer(); 
} 


}; 

假設窗口指針正確指向了主窗口,如果我嘗試打電話runTimer(),我收到此錯誤:

QObject: Cannot create children for a parent that is in a different thread. 
(Parent is MainWindow(0x7fff51ffe9f0), parent's thread is QThread(0x7fd1c8d001d0), current thread is QThread(0x7fd1c8f870c0) 
QObject::startTimer: Timers can only be used with threads started with QThread 

我對這個錯誤的猜測是,因爲runTimer被從另一個線程調用,它也試圖在同一個線程中初始化?而不是主窗口線程?

如果我在主窗口的默認構造函數初始化計時器我收到

QObject::startTimer: Timers cannot be started from another thread 

我怎樣才能把QTimer從另一個類的開始?

回答

1

您可以使用信號和插槽。

class AnotherClass : public QObject 
{ 

    Q_OBJECT 

public: 

    MainWindow * window; 

    AnotherClass() : window(new MainWindow) 
    { 
     // Connect signal to slot (or just normal function, in this case) 
     connect(this, &AnotherClass::signalStartTimer, 
       window, &MainWindow::StartTimer, 
       // This ensures thread safety, usually the default behavior, but it doesn't hurt to be explicit 
       Qt::QueuedConnection); 

     runTimer(); 
    } 

    void runTimer() 
    { 
     emit signalStartTimer(); 
    } 

signals: 

    void signalStartTimer(); 

}; 
+1

不得不改變它來連接(這一點,SIGNAL(signalStartTimer), 窗口,SLOT(startTimer所),QT :: QueuedConnection);但除此之外,它的工作 – Alex