#include <QThread>
它主要的成员函数和数据:
公共类型:枚举
enum Priority { IdlePriority, LowestPriority, LowPriority,NormalPriority, ..., InheritPriority }Public Functions
QThread( QObject *parent = 0 )
~QThread ()
void exit( intreturnCode = 0 )
bool isFinished () const
bool isRunning() const
Priority priority() const
void setPriority ( Prioritypriority )
void setStackSize ( uintstackSize )
uint stackSize() const
bool wait( unsigned longtime = ULONG_MAX )
29 public functions inherited from QObject
Public Slots
void quit()
void start( Prioritypriority = InheritPriority )
void terminate()
1 public slot inherited from QObject
信号
void finished()
void started()
void terminated ()
1 signal inherited from QObject
保护函数
int exec()
virtual void run()
7 protected functions inherited from QObject
静态保护成员
void msleep( unsigned longmsecs )
void setTerminationEnabled ( boolenabled = true )
void sleep( unsigned longsecs )
void usleep( unsigned longusecs )
我们看个例子:
三个文件:mythreaed.h mythread.cpp main.cpp
mythreaed.h:
#ifndef MYTHREAD_H
#define MYTHREAD_H
#include <QThread>
#include <QDebug>
class mythread : public QThread
{
Q_OBJECT
public:
mythread(QObject *parent);
~mythread();
void run();
private slots://声明三个槽
void started_slot();
void finished_slot();
void terminated_slot();
private:
};
#endif // MYTHREAD_H
mythread.cpp :
#include "mythread.h"
mythread::mythread(QObject *parent)
: QThread(parent)
{
//三个信号对应三个槽
this->connect(this,SIGNAL(started()),this,SLOT(started_slot()));
this->connect(this,SIGNAL(finished()),this,SLOT(finished_slot()));
this->connect(this,SIGNAL(terminated()),this,SLOT(terminated_slot()));
}
mythread::~mythread()
{
}
void mythread::run()
{
int i=0;
for (i=0;i<10;i++)
{
sleep(1);//单位是秒
qDebug()<<i;
}
if (i==10)
{
this->quit();
}
else
{
this->terminate();
}
exec();
}
void mythread::started_slot()
{
qDebug()<<"started"<<endl;
}
void mythread::finished_slot()
{
qDebug()<<"finished"<<endl;
}
void mythread::terminated_slot()
{
qDebug()<<"terminated"<<endl;
}
main.cpp:
#include<QtCore/QCoreApplication>
#include "mythread.h"
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
mythread *d=new mythread(0);
d->setPriority(QThread::TimeCriticalPriority);//设置优先级
d->setStackSize(100);//设置栈的大小
d->start();//进程开始
d->wait();
return a.exec();
}