首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从另一个类启动QTimer

从另一个类启动QTimer
EN

Stack Overflow用户
提问于 2016-05-14 03:07:55
回答 1查看 834关注 0票数 0

我有以下课程:

代码语言:javascript
复制
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(),就会收到以下错误:

代码语言:javascript
复制
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是从另一个线程调用的,所以它也试图在同一个线程中初始化?而不是主窗口线程?

如果我在接收到的主窗口的默认构造函数中初始化计时器

代码语言:javascript
复制
QObject::startTimer: Timers cannot be started from another thread

如何让QTimer从另一个类开始?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-05-14 03:24:16

你可以使用信号和插槽。

代码语言:javascript
复制
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
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/37222069

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档