一、练习要求
1、使用QT的IO读取文件;
2、以QSlider为基础,写一个进度条,显示文件读取的进度;
3、给QSlider布置qss样式,qss文件像css文件一样,分离出来。
二、源码
全部源码
源码目录:
1.1 、myeventlooper.h
class MyEventLooper : public QObject
{Q_OBJECT
public:explicit MyEventLooper();void moveToThread(QThread *thread);void startReadFile(QString filename);
signals://进度条成长信号,当percent=100时,表示完成void processGoSig(int percent);void loopSig();
public slots:void rcvLoopSig();private:bool readFlag=false;QFile file;unsigned int cntRead=0;
};
1.2、 myeventlooper.cpp
MyEventLooper::MyEventLooper()
{QObject::connect(this, &MyEventLooper::loopSig, this, &MyEventLooper::rcvLoopSig);
}void MyEventLooper::moveToThread(QThread *thread)
{QObject::moveToThread(thread);emit loopSig();
}void MyEventLooper::startReadFile(QString filename)
{qDebug() << "startReadFile" ;file.setFileName(filename);file.open(QFile::ReadOnly);readFlag=true;
}void MyEventLooper::rcvLoopSig()
{while(1){QThread::msleep(200);if(readFlag == false)continue;//1k1k的读取文件,为了看进度条的效果char data[1024];qint64 cnt=file.read(data, 1024);cntRead += cnt;unsigned int size=file.size();//if(cntRead >= size){file.close();readFlag=false;}emit processGoSig(cntRead*100/size);}
}
2.1、 widget.h
class Widget : public QWidget
{Q_OBJECTpublic:Widget(QWidget *parent = nullptr);~Widget();private slots:void on_btnCho_clicked();void on_btnLoad_clicked();void rcvProcessGoSig(int percent);private:Ui::Widget *ui;MyEventLooper* looper;QThread* t;
};
2.2、 widget.cpp
Widget::Widget(QWidget *parent): QWidget(parent), ui(new Ui::Widget)
{ui->setupUi(this);////t=new QThread(this);looper = new MyEventLooper();QObject::connect(looper,&MyEventLooper::processGoSig, this, &Widget::rcvProcessGoSig);looper->moveToThread(t);t->start();
}Widget::~Widget()
{t->terminate();delete ui;
}void Widget::on_btnCho_clicked()
{QString filename=QFileDialog::getOpenFileName(this, "选择文件", "C:/Users/zhuorui/Desktop");qDebug() << "filename:" << filename;ui->label->setText(filename);
}void Widget::on_btnLoad_clicked()
{//加载文件// QFile file(ui->label->text());// if(!file.open(QFile::ReadOnly)){// qDebug() << "文件读取失败";// return ;// }// file.close()//读取文件中的内容looper->startReadFile(ui->label->text());
}void Widget::rcvProcessGoSig(int percent)
{qDebug() << "rcvProcessGoSig。 percent="<<percent;ui->slider->setValue(percent);if(percent >= 100){QMessageBox::information(this,"提示","文件读取完成");}
}
3.1、 main.cpp
int main(int argc, char *argv[])
{QApplication a(argc, argv);Widget w;QFile file(":/style.css");file.open(QFile::ReadOnly);QString sheet=QString::fromLocal8Bit(file.readAll());file.close();qDebug() << "sheet:" << sheet;a.setStyleSheet(sheet);w.show();return a.exec();
}
3.2、 style.css
QSlider{background-color:red;
}/*QSlider::groove:horizontal{background-color:green;
}QSlider::sub-page{background-color:green;
}*/QSlider::sub-page:horizontal{background-color: rgba(0,255,0,200);
}QSlider::groove:horizontal{background-color: gray;
}