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

QT迷宫项目详解:多线程动画

2018-03-18 17:39 309 查看
学习布局、多线程如何动起来,当然了,还有迷宫的递归代码。
一赏:



输入,点击show。出现了,我的头像



点击按钮,设置障碍,还是我:



点击go,动态寻找路径,注意是动画的:



开源项目: https://github.com/zhuimengshaonian66/maze-by-QT
第一步:设置UI,



2、处理文本框输入后,绘制方格。
QT的布局还是很容易的。免费送上精彩的auto,你是真的懂c++吗。
void Widget::on_btnshow_clicked()
{
// ui->btnGo->setEnabled(false);
//for(vector<vector<MyButton*> >::iterator p = btns.begin(); p != btns.end(); p++)
//{
//  for (vector<MyButton *>::iterator q = p->begin(); q != p->end(); q++)
    //{
//  delete *q;
//}
//}
// ui->btnGo->setEnabled(false);
// for(vector<vector<MyButton*> >::iterator p = btns.begin(); p != btns.end(); p++)
// {
//   for (vector<MyButton *>::iterator q = p->begin(); q != p->end(); q++)
//{
//      delete *q;
//   }
//  }
bool ok;
int num = ui->lineEdit->text().toInt(&ok);
if(!ok){
return;
}
ui->btngo->setEnabled(false);
for(auto p = btns.begin();p!=btns.end();p++){
for(auto q = p->begin();q!=p->end();q++){
delete *q;
}
}
btns.clear();
QVector<mybutton*> temp;
for(int i = 0;i<num;i++){
for(int j = 0;j<num;j++){
mybutton *btn = new mybutton;
ui->gridLayout->addWidget(btn,i,j,1,1);
temp.push_back(btn);
}
btns.push_back(temp);
temp.clear();
}
ui->btngo->setEnabled(true);
}


处理鼠标点击后的变色事件:
void mybutton::mousePressEvent(QMouseEvent *e)
{
empty = !empty;
if (!empty)
{
this->setStyleSheet("background-color:rgb(0, 0, 0);");
}
else
{
this->setStyleSheet("background-color:rgb(255, 255, 255);");
}
}
void mybutton::on()
{
this->setStyleSheet("background-color:rgb(255, 0, 0);");
}
void mybutton::off()
{
this->setStyleSheet("background-color:rgb(255, 255, 255);");
}

新开一个线程,处理迷宫寻路。注意,要动态必须新开一个线程
e.processEvents();这个函数非常重要,是能够动态的关键
This function is especially useful if you have a long running operation and want to show its progress without allowing user input
QThread::msleep(200);不要动的太快,啊啊啊~


递归代码值得你品味,绝对是最优秀之一
void Widget::on_btngo_clicked()
{
ui->btnshow->setEnabled(false);
ui->btngo->setEnabled(false);
delete t;
t=new mythread(&btns,ui->btnshow);
t->run();
}
#include "mythread.h"
mythread::mythread(QVector<QVector<mybutton *> > *_btns, QPushButton * _btnStart)
{
this->btns = _btns;
this->btnStart =_btnStart;
}
void mythread::run()
{
go(0, 0);
btnStart->setEnabled(true);
}
bool mythread::go(int x, int y)
{
if (x < 0 || y < 0 || x >= btns->size() || y >= btns->size())
{
return false;
}
if (!(*btns)[y][x]->getEmpty())
{
return false;
}
e.processEvents();
QThread::msleep(200);
if (x == btns->size() - 1 && y == btns->size() - 1)
{
(*btns)[y][x]->on();
return true;
}
for(QVector<QPair<int, int> >::iterator p = his.begin(); p != his.end(); p++)
{
if (p->first == x && p->second == y)
{
return false;
}
}
(*btns)[y][x]->on();
his.push_back(QPair<int, int>(x, y));
if (go(x, y + 1) || go(x + 1, y) || go(x, y - 1) || go(x - 1, y))
{
return true;
}
(*btns)[y][x]->off();
return false;
}

                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  qt 迷宫 多线程