c++ - 使用 Qt 和 QThread 的简单数字时钟

标签 c++ multithreading qt signals-slots

我想使用 Qt 框架创建一个程序。目的是编写一个程序,使用 QThread 来显示一个简单的数字时钟。但是运行时没有任何反应。

这是运行的Qthread的子类

paytamtimers.h

#ifndef PAYTAMTIMERS_H
#define PAYTAMTIMERS_H
#include <QThread>

class PaytamTimers:public QThread
{
    Q_OBJECT
public:
    PaytamTimers();
QString now;
protected:
    virtual void run();
private:
    QMutex mutex;
    QThread *thread;

signals:
    void mySignal(QString);
};

#endif // PAYTAMTIMERS_H

这是this.class的实现 支付宝.cpp

#include "paytamtimers.h"
#include <QTime>

PaytamTimers::PaytamTimers()
{
    this->now="";
    this->thread=new QThread(0);
}

void PaytamTimers::run(){
forever{
    mutex.lock();
    this->now=QTime::currentTime().toString();
    this->thread->sleep(1000);
    emit mySignal(this->now);
    mutex.unlock();

}
}

这是GUI形式的实现。这由 QLabel 和一个 paytamtimers 实例组成,只是为了简单起见

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "paytamtimers.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    t=new PaytamTimers();
    t->start();
    connect(t,SIGNAL(t->mySignal(QString)),this,SLOT(this->now(const QString &string)));
}

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

void MainWindow::now(const QString &string){
    this->ui->label->setText(t->now);
}

最佳答案

  1. 在线程休眠时不应该持有互斥量。事实上,你的互斥量是完全没有必要的。

  2. 您的connect 语句是错误的,如hyde 所指出的那样. this 参数是隐含的,因此您可以简单地说:

    connect(t, SIGNAL(mySignal(QString)), SLOT(now(QString)));
    
  3. 您不需要使用线程来发出周期性时间更新。

您的 MainWindow 可能如下所示。它会尽可能接近整秒来触发计时器事件。

class MainWindow : public QWidget {
    Q_OBJECT
    QBasicTimer m_timer;
    void timerEvent(QTimerEvent * ev) {
        if (ev->timerId() == m_timer.timerId()) {
            QTime t = QTime::currentTime();
            m_timer.start(1000 - t.msec(), this);
            // round to nearest second
            if (t.msec() < 500) t = t.addMsecs(-t.msec()); else t = t.addMSecs(1000-t.msec());
            now(t.toString());
        }
    }
    void now(const QString &);
    ...
public:
    MainWindow(QWidget *parent = 0) : QWidget(parent) {
        m_timer.start(1000 - QTime::currentTime().msec(), this);
    }
};

关于c++ - 使用 Qt 和 QThread 的简单数字时钟,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18643818/

相关文章:

c++ - C++ 标准的哪一部分允许在括号中声明变量?

C++ 智能指针地址

c++ - 调试优化的构建是否会导致程序表现不同?

c++ - 段错误 - 已使用新的和删除的。在运行时正在创建大量数组(无界数组)

java - 以有限的执行次数高效地线程安全地实现业务服务操作

c++ - 如何在QScrollArea上绘制QImage?这样做了,但是有一些小问题 QPainter::begin: Widget painting can only begin as a result of a paintEvent

java - 使用了Java CompletableFuture线程池

multithreading - Service 和 Web Worker 之间的技术差异

c++ - 没有匹配的函数来调用 'connect'(QT)

c++ - 使用 Qt 生成自签名 SSL 证书