我想使用 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);
}
最佳答案
在线程休眠时不应该持有互斥量。事实上,你的互斥量是完全没有必要的。
您的
connect
语句是错误的,如hyde 所指出的那样.this
参数是隐含的,因此您可以简单地说:connect(t, SIGNAL(mySignal(QString)), SLOT(now(QString)));
您不需要使用线程来发出周期性时间更新。
您的 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/