您的位置:首页 > 编程语言 > Qt开发

qt多线程一个简单的例子

2014-03-12 13:29 411 查看
作者:zgrjkflmkyc

转自:/article/8178732.html

代码如下:

[cpp]
view plaincopy

/**********Main.cpp*************/

#include <QtGui/QApplication>
#include "MainWindow.h"

int main(int argc,char *argv[]){
QApplication a(argc,argv);
MainWindow window;
window.show();
return a.exec();
}

[cpp]
view plaincopy

/************MainWindow.h**************/

#ifndef MINWINDOW_H_
#define MINWINDOW_H_

#include <QtGui/QWidget>
#include "MyThread.h"
#include <QtGui/QPushButton>

class MainWindow : public QWidget
{
public:
MainWindow(QWidget *parent = 0);
~MainWindow();
MyThread *thread;
QPushButton *pb;
};

#endif

[cpp]
view plaincopy

/*************MainWindow.cpp****************/

#include "MainWindow.h"

MainWindow::MainWindow(QWidget *parent) : QWidget(parent)
{
this->setGeometry(0,0,300,300);
pb=new QPushButton("AA",this);
pb->setGeometry(0,0,30,30);
thread=new MyThread(pb);
thread->start();
}

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

[cpp]
view plaincopy

/***************MyThread.h******************/

#include <QtCore/QThread>
#include <QtGui/QPushButton>

class MyThread : public QThread
{
Q_OBJECT
public:
MyThread(QPushButton *pb);
~MyThread();
QPushButton *pb;
protected:
void run();
};

[cpp]
view plaincopy

/**************MyThread.cpp*****************/

#include "MyThread.h"
#include <iostream>

MyThread::MyThread(QPushButton *pb) : QThread()
{
this->pb=pb;
}

void MyThread::run(){
int i=1;
while(true){
std::cout<<"the number is:"<<i<<std::endl;
QThread::msleep(1000);
i+=10;
pb->move(i,i);
}
}

MyThread::~MyThread()
{

}

编译前最终的.pro文件内容:

[plain]
view plaincopy

######################################################################
# Automatically generated by qmake (2.01a) ?? 6? 15 23:36:31 2013
######################################################################

TEMPLATE = app
TARGET =
DEPENDPATH += .
INCLUDEPATH += .

# Input
HEADERS += MainWindow.h MyThread.h
SOURCES += Main.cpp MainWindow.cpp MyThread.cpp

编译前最终的Makefile片段:

[plain]
view plaincopy

CC = gcc
CXX = g++
DEFINES = -DQT_WEBKIT -DQT_NO_DEBUG -DQT_GUI_LIB -DQT_CORE_LIB -DQT_SHARED
CFLAGS = -pipe -O2 -Wall -W -D_REENTRANT $(DEFINES)
CXXFLAGS = -pipe -O2 -Wall -W -D_REENTRANT $(DEFINES)
INCPATH = -I/usr/share/qt4/mkspecs/linux-g++ -I. -I/usr/include/qt4/QtCore -I/usr/include/qt4/QtGui -I/usr/include/qt4 -I. -I.
LINK = g++
LFLAGS = -Wl,-O1
LIBS = $(SUBLIBS) -L/usr/lib/i386-linux-gnu -lQtGui -lQtCore -lpthread
AR = ar cqs
RANLIB =
QMAKE = /usr/bin/qmake
TAR = tar -cf
COMPRESS = gzip -9f
COPY = cp -f
SED = sed
COPY_FILE = $(COPY)
COPY_DIR = $(COPY) -r
STRIP = strip
INSTALL_FILE = install -m 644 -p
INSTALL_DIR = $(COPY_DIR)
INSTALL_PROGRAM = install -m 755 -p
DEL_FILE = rm -f
SYMLINK = ln -f -s
DEL_DIR = rmdir
MOVE = mv -f
CHK_DIR_EXISTS= test -d
MKDIR = mkdir -p

运行效果截图:



(仅供参考)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: