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

Qt5实现打地鼠

2016-01-19 20:04 411 查看
最近放寒假在家闲来无事把以前写的东西写下,做下记录,实现打地鼠基本功能。

效果图:



百度网盘分享:http://pan.baidu.com/s/1eRtWDKe

最要是自定义的按钮,也就是老鼠出来的小窗体,还有线程,以及主窗口。

下面是主要代码,

自定义按钮:

#include “mybutton.h”

MyButton::MyButton(QWidget *parent) :

QPushButton(parent)

{

stopflag=true;

downup=true;

mouse_heigth=0;

timer_=new QTimer(this);

connect(timer_,SIGNAL(timeout()),this,SLOT(showimage()));

this->setMaximumSize(120,120);
this->setMinimumSize(120,120);
setEnabled(true);
setChecked(true);


// this->setAutoFillBackground(true);

// QPixmap pix(“:/images/hole.jpg”);

// pix=pix.scaled(this->width(),this->height());

// QPalette pale;

// pale.setBrush(QPalette::Button,QBrush(pix));

// setPalette(pale);

// update();

}

void MyButton::paintEvent(QPaintEvent *)

{

QImage img;

img.load(“:/images/u.gif”);

QRectF s(0,this->height()-mouse_heigth,this->width(),this->height());
QRectF t(0,0,this->width(),this->height());
QPainter painter(this);
painter.drawImage(s,img,t);
update();


}

void MyButton::mousePressEvent(QMouseEvent *e)

{

QPixmap pix(“:/images/bt03.png”);

if(e->button()==Qt::LeftButton)

this->setCursor(QCursor(pix));

e->accept();

this->click();

}

void MyButton::mouseReleaseEvent(QMouseEvent *e)

{

QPixmap pix(“:/images/bt001.png”);

if(e->button()==Qt::LeftButton)

this->setCursor(QCursor(pix));

e->accept();

}

void MyButton::showimage()

{

if(!downup&&mouse_heigth<=0){

timer_->stop();

}
if(downup){
mouse_heigth+=1;
if(mouse_heigth>=this->height())
downup=!downup;
}
if(!downup){
mouse_heigth-=1;
if(mouse_heigth<0)
downup=!downup;

}

update();


}

void MyButton::timestart()

{

timer_->start(10);

}

线程函数:

#include “thread.h”

Thread::Thread(QObject *parent) :

QThread(parent)

{

stopFlag = true;

}

void Thread::stopThread()

{

stopFlag = true;

this->exit();

// this->quit();

// this->terminate();

}

void Thread::run()

{

if(!stopFlag){

// stopFlag=!stopFlag;

return;

}

stopFlag = false;

qsrand(QTime::currentTime().second());

int cur_index = 0;
int tmp_index = 0;
while(!stopFlag){
cur_index = qrand() % 9;
if(tmp_index == cur_index)
continue;
tmp_index = cur_index;
emit  sendRandDigit(cur_index);
usleep(1000*1000);


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