c++ - 从另一个类启动 QTimer

标签 c++ multithreading qt qtimer

我有以下类(class):

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 从另一个类开始?

最佳答案

您可以使用信号和槽。

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();

};

关于c++ - 从另一个类启动 QTimer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37222069/

相关文章:

c++ - 尝试等待 boost::condition_Variable 时出现 "unique_lock has no mutex: Operation not permitted"错误

c++ - QTimer每秒执行一次方法

c++ - 在 C++ 应用程序中使用 libgrib2c,链接器错误 "Undefined reference to..."

c++ - 委派 OnUpdate ... MFC 中来自 CMainFrame 的消息

c++ - 线程安全的 std::map:锁定整个映射和单个值

c++ - 跟踪 C 中的整数列表,并从列表中采样

multithreading - 使用 spark-submit,--total-executor-cores 选项的行为是什么?

c++ - QCustomPlot/Widget 不显示图形/更新

c++ - 在 C++ 中定义自己的异常类

c++ - 在 C++ 中将临时插入 vector