对于多线程而言,要注意资源的同步和互斥问题,但对于单独的一个线程,则只需要对它的run方法进行重写。
下面实现了一个简单的线程
widget.h文件
#ifndef WIDGET_H #define WIDGET_H #include <QWidget> #include <QPushButton> #include <QLineEdit> #include <QHBoxLayout> #include <QVBoxLayout> #include <QTime> #include <QTimer> #include "mythread.h" class Widget : public QWidget { Q_OBJECT public: Widget(QWidget *parent = 0); ~Widget(); private slots: void settime(); void startThread(); private: QPushButton *pb_start,*pb_stop; QLineEdit *le; QTimer *time; myThread *thread; }; #endif // WIDGET_H
widget.cpp文件
#include "widget.h" Widget::Widget(QWidget *parent) : QWidget(parent) { pb_start = new QPushButton("start"); pb_stop = new QPushButton("stop"); le = new QLineEdit; le->setAlignment(Qt::AlignCenter); QTime t = QTime::currentTime(); le->setText(t.toString("hh:mm:ss")); QHBoxLayout *hbox = new QHBoxLayout; hbox->addWidget(pb_start); hbox->addWidget(pb_stop); QVBoxLayout *vbox = new QVBoxLayout; vbox->addWidget(le); vbox->addLayout(hbox); setLayout(vbox); time = new QTimer; time->start(1000); thread = new myThread; connect(time,SIGNAL(timeout()),this,SLOT(settime())); connect(pb_start,SIGNAL(clicked(bool)),this,SLOT(startThread())); connect(pb_stop,SIGNAL(clicked(bool)),thread,SLOT(terminate())); } Widget::~Widget() { } void Widget::settime() { QTime t = QTime::currentTime(); le->setText(t.toString("hh:mm:ss")); } void Widget::startThread() { thread->start(); }
mythread.h文件
#ifndef MYTHREAD_H #define MYTHREAD_H #include <QThread> #include <QWidget> #include <QDebug> class myThread : public QThread { Q_OBJECT public: myThread(); protected: void run(); }; #endif // MYTHREAD_H
mythread.cpp文件
#include "mythread.h" myThread::myThread() { } void myThread::run() { for(int i=0; ;i++) { sleep(1); qDebug()<<"i = "<<i; } }
运行结果