简体   繁体   English

为什么QTimer不异步?

[英]Why isn't QTimer asynchronous?

I tried to use a simple QTimer object on my window widget so that I can calculate the elapsed time a method takes to complete. 我试图在我的窗口小部件上使用一个简单的QTimer对象,以便我可以计算出方法完成所花费的时间。 But to my astonishment, the timer was blocked until the method completes execution! 但令我惊讶的是,计时器一直被阻塞,直到方法完成执行为止! ie when the method in question ends, the timer starts ticking! 也就是说,当相关方法结束时,计时器开始计时!

Here is a sample code to demonstrate what I wrote: 这是一个示例代码来演示我写的内容:

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>

namespace Ui {
  class MainWindow;
}

class MainWindow : public QMainWindow
{
  Q_OBJECT

public:
  explicit MainWindow(QWidget *parent = 0);
  ~MainWindow();

private slots:
  void on_btnTest_clicked();
  void OnTimerTick();

private:
  Ui::MainWindow *ui;
  ulong seconds;
};

#endif // MAINWINDOW_H  

And this is the cpp file: 这是cpp文件:

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "opencv2/core/core.hpp"
#include "opencv2/highgui/highgui.hpp"
#include "opencv/cv.h"
#include <QTimer>
#include <QtCore>

MainWindow::MainWindow(QWidget *parent) :
  QMainWindow(parent),
  ui(new Ui::MainWindow)
{
  ui->setupUi(this);
}

MainWindow::~MainWindow()
{
  delete ui;
}


void MainWindow::on_btnTest_clicked()
{
  QTimer * timer = new QTimer(0);
  seconds =0;
  connect(timer,SIGNAL(timeout()),this,SLOT(OnTimerTick()));

  timer->setInterval(100);
  timer->start();

 QThread::sleep(5);//simulating a method which takes 5 seconds to complete

 //timer->stop();   

}

void MainWindow::OnTimerTick()
{
  ui->lblElapsedTime->setText(QString::number(++seconds));
}

How can I get the asynchronous behavior, something like what we have in C# ie where the Timer runs its own thread of execution? 我如何获得异步行为,就像我们在C#中一样,即Timer在其中运行自己的执行线程?

Update: 更新:
Thanks for the clarification, now how can I incorporate Qthreads with the timer, Do I have to inherit from Qthreads and use timer in my child class or do I have to inherit from QTimer and have a thread executed in it! 感谢您的澄清,现在我如何将Qthreads与计时器合并,我是否必须从Qthreads继承并在子类中使用timer,还是必须从QTimer继承并在其中执行线程! It's really confusing! 真是令人困惑!

This is common behavior for Qt, WinForms, WPF etc. 这是Qt,WinForms,WPF等的常见行为。

All UI-related events are executed synchronously one-by-one on the UI thread. 所有与UI相关的事件都在UI线程上一对一地同步执行。 Event handlers are not expected to perform long executions to avoid blocking. 不应期望事件处理程序执行长时间执行以避免阻塞。 If you want to execute a long task, you should do it in other thread. 如果要执行较长的任务,则应在其他线程中执行。

QTimer is designed to raise events on the UI thread. QTimer旨在引发UI线程上的事件。 This is good because you are sure that no other event handlers are executing at that moment. 这很好,因为您可以确定此时没有其他事件处理程序在执行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM