QT 发射信号,接收槽,双线程演示(QtSDK演示程序)

#ifndef CLOCKTHREAD_H
#define CLOCKTHREAD_H
 
#include <QString>
#include <QThread>
 
 
// clock/clockthread.h
class ClockThread : public QThread
{
    Q_OBJECT
signals:
    void sendTime(QString time);
private:
    void run();
    QString m_lastTime;
private slots:
    void timerHit();
 
};
#endif // CLOCKTHREAD_H

=================
#include <QtGui>
#include "clockthread.h"
 //This class starts another thread where it emits a signal for every new second.
// clock/clockthread.cpp
void ClockThread::run()
{
    QTimer timer;
    connect(&timer, SIGNAL(timeout()), this, SLOT(timerHit()), Qt::DirectConnection);
    timer.setInterval(10);
    timer.start();   // puts one event in the threads event queue
    exec();
    timer.stop();
}
void ClockThread::timerHit()
{
    QString newTime= QDateTime::currentDateTime().toString("ddd MMMM d yy, hh:mm:ss");
    if(m_lastTime != newTime ){
        m_lastTime = newTime;
        emit sendTime(newTime) ;
    }
}

=============================

#include <QtGui>
#include "clockthread.h"
//A clock that does time formatting in another thread
int main(int argc, char *argv[])
{
    QApplication app(argc, argv);
    // build gui
    QWidget widget;
    QLabel *label = new QLabel;
    QHBoxLayout *layout = new QHBoxLayout(&widget);
    layout->addWidget(label);
    widget.setWindowTitle("clock");
    //instantiate thread object
    ClockThread clockThread;
    QObject::connect(&clockThread, SIGNAL(sendTime(QString)), label, SLOT(setText(QString)), Qt::QueuedConnection);
    clockThread.start();
    widget.show();
    app.exec();
    clockThread.quit();
    clockThread.wait();
    return 0;
}




                
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值