Qt启动C++线程并在线程中修改界面
这里以在线程中访问excel,然后读取完成在界面提示
1、按钮启动线程
void Mystack::on_pushButton_9_clicked() { QString str = QFileDialog::getOpenFileName(this); if(str == "") { return; } std::thread t(&Mystack::getTrackData,this,str); t.detach(); ui->label_147->setText(""); }
2、线程函数
void Mystack::getTrackData(QString path)//path是excel的路径 { (void)CoInitialize(NULL); //读取excel所有数据 QAxObject * excel = new QAxObject("Excel.Application");//选择excel软件 excel->dynamicCall("Setvisible (bool Visible)","false");//不显示主窗体,后面打开excel的时候不显示 excel->setProperty("DisplayAlerts",false);//不显示excel的警告信息,如果打开失败,不弹出框 QAxObject *work_books = excel->querySubObject("WorkBooks");//选择work_books work_books->dynamicCall("Open(const QString&)", path);//设置excel存在路径 QAxObject *work_book = excel->querySubObject("ActiveWorkBook");//选择work_book QAxObject *work_sheet = work_book->querySubObject("Sheets(int)",1); //Sheets也可换用WorkSheets,打开第一个sheet QAxObject *range_data = work_sheet->querySubObject("UsedRange"); QVariant var = range_data->dynamicCall("Value");//将所有数据存在QVariant结构体里面 //excel内存回收 delete range_data; delete work_sheet; delete work_book; delete work_books; delete excel; //获取到所有数据 allDataTvlist.clear(); castVariant2ListListVariant(var,allDataTvlist);//自定义函数 QList<QString> list; QString tmpStr; for(int i=1;i<allDataTvlist.size();i++) { tmpStr = allDataTvlist.at(i).at(0).toString(); if(tmpStr=="批号") { continue; } if(NOT_FOUND==list.indexOf(tmpStr)) { list.append(tmpStr); } } ui->comboBox->clear();//直接访问this的ui对象 foreach (const QString &value, list) { ui->comboBox->addItem(value); } ui->comboBox->setCurrentIndex(0); ui->label_147->setText("请选择指定批号上传"); }
长风破浪会有时,直挂云帆济沧海!
可通过下方链接找到博主
https://www.cnblogs.com/judes/p/10875138.html