void NetworkStatusStatement::onExportExcelButton() { QString filePath = QFileDialog::getSaveFileName(this, tr("请选择要导出的excel文件路径"), "", tr("Excel 文件(*.xls)")); if(filePath == "") return; ExportExcelObject exportExcelObject(filePath, tr("网络日志"), ui->m_EventTable); exportExcelObject.addField(0, tr("事件时间"), "varchar(100)"); exportExcelObject.addField(1, tr("客户端"), "varchar(100)"); exportExcelObject.addField(2, tr("事件种类"),"varchar(20)"); exportExcelObject.addField(3, tr("IP地址"),"varchar(50)"); exportExcelObject.addField(4, tr("端口号"),"varchar(20)"); QProgressDialog progressDialog; progressDialog.setRange(0, ui->m_EventTable->rowCount()); connect(&exportExcelObject, SIGNAL(exportedRowCount(int)), &progressDialog, SLOT(setValue(int))); progressDialog.show(); int ret = exportExcelObject.export2Excel(); if(ret > 0) { QMessageBox::information(this, tr("消息"), tr("恭喜您,Excel文档导出成功!")); } else { QMessageBox::critical(this, tr("错误"), tr("非常抱歉,Excel文档导出失败!")); } }
void Thread::Execute(bool WaitTilDone) { //starts the thread, waits til complete; clock_t startTime, finishTime; startTime = clock(); QProgressDialog progress; progress.setModal(true); if (pCancelFlag) *pCancelFlag = false; //haven't canceled before we started! start(); if (WantProgress) progress.show(); if (WantProgress || WantTimed || WaitTilDone){ //if we want to stick around until the thread is finished... while (isRunning()){ if (WantProgress){ progress.setLabelText(QString((*pCurMessage).c_str())); progress.setRange(0, *pCurMaxTick); progress.setValue(*pCurTick); QApplication::processEvents(); if (progress.wasCanceled()){ *pCancelFlag = true; wait(); return; //returns } } msleep(50); } } finishTime = clock(); double duration = (double)(finishTime - startTime) / CLOCKS_PER_SEC; std::ostringstream os; os << "Elapsed time: " << duration << " Sec"; if (WantTimed) QMessageBox::warning(NULL, "Warning", (os.str()).c_str()); }
void UnnormalClientStatisticDialog::onExportExcelButton() { QString filePath = QFileDialog::getSaveFileName(this, tr("请选择要导出的excel文件路径"), "", tr("Excel 文件(*.xls)")); if(filePath == "") return; ExportExcelObject exportExcelObject(filePath, tr("异常状态统计信息"), m_Table); exportExcelObject.addField(0, tr("客户组名称"), "varchar(100)"); exportExcelObject.addField(1, tr("客户端数目"), "int"); exportExcelObject.addField(2, tr("温度异常数目"),"int"); exportExcelObject.addField(3,tr("湿度异常数目"),"int"); exportExcelObject.addField(4, tr("开关一异常数目"),"int"); exportExcelObject.addField(5, tr("门磁异常数目"),"int"); exportExcelObject.addField(6,tr("开关二异常数目"),"int"); exportExcelObject.addField(7,tr("开关三屏异常数目"),"int"); exportExcelObject.addField(8, tr("总异常数目"),"int"); QProgressDialog progressDialog; progressDialog.setRange(0, m_Table->rowCount()); connect(&exportExcelObject, SIGNAL(exportedRowCount(int)), &progressDialog, SLOT(setValue(int))); progressDialog.show(); int ret = exportExcelObject.export2Excel(); if(ret > 0) { QMessageBox::information(this, tr("消息"), tr("恭喜您,Excel文档导出成功!")); } else { QMessageBox::critical(this, tr("错误"), tr("非常抱歉,Excel文档导出失败!")); } }
void FileTransferLogDialog::onExportExcelButton() { QString filePath = QFileDialog::getSaveFileName(this, tr("请选择要导出的excel文件路径"), "", tr("Excel 文件(*.xls)")); if(filePath == "") return; ExportExcelObject exportExcelObject(filePath, tr("文件传送日志"), ui->m_LogTable); exportExcelObject.addField(0, tr("客户端"), "varchar(100)"); exportExcelObject.addField(1, tr("文件名"), "varchar(100)"); exportExcelObject.addField(2, tr("文件大小KB"),"int"); exportExcelObject.addField(3, tr("传送结束时间"),"varchar(100)"); QProgressDialog progressDialog; progressDialog.setRange(0, m_Model->rowCount()); connect(&exportExcelObject, SIGNAL(exportedRowCount(int)), &progressDialog, SLOT(setValue(int))); progressDialog.show(); int ret = exportExcelObject.export2Excel(); if(ret > 0) { QMessageBox::information(this, tr("消息"), tr("恭喜您,Excel文档导出成功!")); } else { QMessageBox::critical(this, tr("错误"), tr("非常抱歉,Excel文档导出失败!")); } }
int QgsRasterFileWriter::pyramidsProgress( double dfComplete, const char *pszMessage, void* pData ) { Q_UNUSED( pszMessage ); GDALTermProgress( dfComplete, 0, 0 ); QProgressDialog* progressDialog = static_cast<QProgressDialog*>( pData ); if ( pData && progressDialog->wasCanceled() ) { return 0; } if ( pData ) { progressDialog->setRange( 0, 100 ); progressDialog->setValue( dfComplete * 100 ); } return 1; }
bool Omr::readPdf() { QProgressDialog *progress = new QProgressDialog(QWidget::tr("Reading PDF..."), QWidget::tr("Cancel"), 0, 100, 0, Qt::FramelessWindowHint); progress->setWindowModality(Qt::ApplicationModal); progress->show(); progress->setRange(0, ACTION_NUM); #ifdef OCR if (_ocr == 0) _ocr = new Ocr; _ocr->init(); #endif int ID = READ_PDF; int page = 0; bool val; while (ID < ACTION_NUM) { if(ID != INIT_PAGE && ID != SYSTEM_IDENTIFICATION) { page = 0; progress->setLabelText(QWidget::tr("%1 at Page %2").arg(ActionNames.at(ID+1)).arg(1)); val = omrActions(ID, page); } else { progress->setLabelText(QWidget::tr("%1 at Page %2").arg(ActionNames.at(ID)).arg(page+1)); val = omrActions(ID, page); page++; } if (!val || progress->wasCanceled()) { progress->close(); return false; } else { if (ID < ACTION_NUM) progress->setValue(ID); else progress->setValue(ACTION_NUM - 1); qApp->processEvents(); } } progress->close(); delete progress; return true; }
void MountainViewWidgetPrivate::update_clips_view(SSTimeSeriesWidget *W,SSTimeSeriesView *V,int label) { QProgressDialog dlg; dlg.setWindowTitle(QString("Extracting clips for template %1").arg(label)); dlg.setRange(0,100); dlg.show(); dlg.setLabelText(QString("Extracting clips for template %1...").arg(label)); dlg.setValue(0); dlg.repaint(); qApp->processEvents(); Mda clips=extract_clips(m_raw,m_times,m_labels,label); dlg.setLabelText("Formatting clips..."); dlg.setValue(50); dlg.repaint(); qApp->processEvents(); Mda clips2=format_clips(clips,m_template_view_padding); DiskArrayModel *MM=new DiskArrayModel; MM->setFromMda(clips2); dlg.setLabelText("Initializing..."); dlg.setValue(75); dlg.repaint(); qApp->processEvents(); V->setData(MM,true); V->initialize(); W->setClipData(clips); W->setWindowTitle(QString("Spike Clips -- template %1 -- %2 spikes").arg(label).arg(clips.N3())); }
void ShortestPathComputer::init(ccMesh *mesh, QWidget *parentWidget/* = NULL*/) { mMesh = mesh; ccGenericPointCloud *cloud = mesh->getAssociatedCloud(); const unsigned vertexNum = cloud->size(); const unsigned triangleNum = mesh->size(); const unsigned edgeNum = triangleNum * 3; //半边 Edge *edges = new Edge[edgeNum]; float *edgeWeights = new float[edgeNum]; const unsigned triangleEdgeVertexIndexs[3][2] = { 0, 1, 1, 2, 2, 0 }; unsigned edgeIndexBase, edgeIndex; mesh->placeIteratorAtBegining(); for (unsigned i = 0; i < triangleNum; i++) { CCLib::TriangleSummitsIndexes* indexs = mesh->getNextTriangleIndexes(); assert(indexs->i[0] < vertexNum && indexs->i[1] < vertexNum && indexs->i[2] < vertexNum); const CCVector3 *triangleVertices[3] = { cloud->getPoint(indexs->i[0]), cloud->getPoint(indexs->i[1]), cloud->getPoint(indexs->i[2]) }; edgeIndexBase = i * 3; for (unsigned j = 0; j < 3; j++) { edgeIndex = edgeIndexBase + j; edges[edgeIndex].first = indexs->i[triangleEdgeVertexIndexs[j][0]]; edges[edgeIndex].second = indexs->i[triangleEdgeVertexIndexs[j][1]]; edgeWeights[edgeIndex] = CCVector3::vdistance(triangleVertices[triangleEdgeVertexIndexs[j][0]]->u, triangleVertices[triangleEdgeVertexIndexs[j][1]]->u); } } //开启新线程初始化BGL图并显示进度条 BoostGraphInitThread thread; thread.setGraphData(&mGraph, edges, edgeNum, edgeWeights, vertexNum); thread.start(); QProgressDialog progress; if (parentWidget) { progress.setParent(parentWidget); } progress.setWindowModality(Qt::WindowModal); progress.setWindowFlags(Qt::SubWindow | Qt::Popup); progress.setMinimumWidth(200); progress.setCancelButton(0); progress.setWindowTitle(QString::fromAscii("BGL图初始化")); progress.setLabelText(QString::fromAscii("BGL图初始化中,请稍后...")); progress.setRange(0, 0); progress.show(); while (thread.isRunning()) { QApplication::processEvents(); } progress.close(); //mGraph = MyGraph(edges, edges + edgeNum, edgeWeights, vertexNum); }
void MainWindow::importFile() { QFile loadfile(filename); loadfile.open(QIODevice::ReadOnly); QDataStream ls(&loadfile); ls.setByteOrder(QDataStream::BigEndian); ls.device()->seek(3200); Reel.ReadREEL(ls); //Max_XLine=Max_YLine=Min_XLine=Min_YLine=0; DBTrace t; int xLine; //主测线号XLINE int oldxLine; int inLine; //inLine 号 int temp,_temp,N; temp =_temp=0; N=0; QFile writefile(filename+tr("_db")); writefile.open(QIODevice::WriteOnly); QDataStream ws(&writefile); QProgressDialog *pdg = new QProgressDialog(this); QFont font("Times",10,QFont::Bold); pdg->setFont(font); pdg->setWindowModality(Qt::WindowModal); pdg->setWindowTitle(tr("导入SEGY文件")); pdg->setLabelText(tr("扫描SEGY数据")); pdg->setCancelButtonText(tr("取消")); pdg->setRange(0,Reel.TotalTraces); pdg->setMinimumDuration(500); int HNS = Reel.hns; int DataType = Reel.DataType; xLine = oldxLine = 0; pdg->setValue(0); qApp->processEvents(); for( int i = 0; i < Reel.TotalTraces; i ++) { double fp = 3600.0 + 8.0 + double(i)*double(HNS*DataType + 240.0); pdg->setValue(i+1); qApp->processEvents(); if (pdg->wasCanceled()) { break; } ws<<i; ls.device()->seek(fp); ls >>xLine; ls.device()->seek(fp+12.0); ls>>inLine; t.fp = i; t.in = xLine; t.cross = inLine; t.st = 0; t.et = Reel.hns*Reel.hdt/1000; CdbTrace->AddData(t); if( i == 0 ) { Max_XLine = xLine; Min_XLine = xLine; Max_YLine = inLine; Min_YLine = inLine; } else { if( xLine > Max_XLine ) Max_XLine = xLine; if( xLine < Min_XLine ) Min_XLine = xLine; if( inLine > Max_YLine ) Max_YLine = inLine; if( inLine < Min_YLine ) Min_YLine = inLine; } } loadfile.close(); /**/ reelAction->setEnabled(true); traceAction->setEnabled(true); dataAction->setEnabled(true); }
bool AirportsData::import(QProgressDialog &progress, MainObject *mainObject){ QHash<QString, QString> airports; QString msg; QTime tm; int ms; progress.setValue(0); progress.setWindowTitle("Scanning Airport Directories"); progress.setRange(0, 50000); int c = 0; int found = 0; int air_added = 0; ms = tm.restart(); // Removing cache file, if exists() if (QFile::exists(mainObject->data_file("airports.txt"))) { outLog("*** FGx airportsdata reload: cache file exists!"); QFile::remove(mainObject->data_file("airports.txt")); outLog("*** FGx airportsdata reload: REMOVED AIRPORTS CACHE FILE"); } //= Cache File QFile cacheFile( mainObject->data_file("airports.txt") ); if(!cacheFile.open(QIODevice::WriteOnly | QIODevice::Text)){ //qDebug() << "TODO Open error cachce file="; return true; } QTextStream out(&cacheFile); msg = "FGx airportsdata reload: Scanning apt.dat.gz in " + mainObject->X->fgroot() + "/Airports/apt.dat.gz"; outLog(msg); airports = getAirportNameMap(mainObject); //================================================ //* Lets Loop the directories //* Get out aiports path from setings and get the the subdir also QDirIterator loopAirportsFiles( mainObject->X->airports_path(), QDirIterator::Subdirectories ); QString xFileName; msg = "FGx airportsdata reload: Scanning XML files in "+mainObject->X->airports_path(); outLog(msg); progress.setWindowTitle(msg); progress.setRange(0, 50000); // Check the fgfs additional argument list, // and/or any additional scenery path inputs // *** take care NOT to duplicate *** QStringList fgfs_args = mainObject->X->get_fgfs_args(); int i, ind; QDir d; QString path; #ifdef Q_OS_WIN QChar psep(';'); #else QChar psep(':'); #endif // AIIIIII, found the doubler !, said yves very very loud - well done said pete ;-) for (i = 0; i < fgfs_args.size(); i++) { msg = fgfs_args.at(i); ind = msg.indexOf(QChar('"')); if (ind == 0) msg = msg.mid(1,msg.length()-2); if (msg.indexOf("--fg-scenery=") == 0) { // got a scenery folder to scan msg = msg.mid(13); ind = msg.indexOf(QChar('"')); if (ind == 0) msg = msg.mid(1,msg.length()-2); QStringList path_list = msg.split(psep); int pathnumber = 0; for( QStringList::ConstIterator entry = path_list.begin(); entry != path_list.end(); entry++) { path = *entry; pathnumber = pathnumber + 1; if (d.exists(path)) { // we have a PATH to check, but we are ONLY checking 'Airports' if ( !(path.indexOf(QChar('/')) == (path.size()-1)) && !(path.indexOf(QChar('\\')) == (path.size()-1)) ) path.append("/"); path.append("Airports"); // XML is only in here if (!d.exists(path)) continue; QDirIterator loopFiles( path, QDirIterator::Subdirectories ); while (loopFiles.hasNext()) { //= Get file handle if there is one xFileName = loopFiles.next(); //= Check if file entry is a *.threshold.xml - cos this is what we want if(xFileName.endsWith(".threshold.xml") ){ //= Split out "CODE.threshold.xml" with a "." QFileInfo fileInfoThreshold(xFileName); QString airport_code = fileInfoThreshold.fileName().split(".").at(0); //* Update progress if(c % 100 == 0){ progress.setValue(c); progress.setLabelText(xFileName); progress.repaint(); } QString airport_name(""); if(airports.contains(airport_code)){ airport_name = airports.value(airport_code); } QStringList cols; // missing in middle is description ?? cols << airport_code << airport_name << fileInfoThreshold.absoluteDir().absolutePath() << QString::number(pathnumber); out << cols.join("\t").append("\n"); air_added++; found++; } if(progress.wasCanceled()){ progress.hide(); return true; } c++; } } } } } cacheFile.close(); msg.sprintf("*** FGx airportsdata reload: Walked %d files, found %d threshold.xml, appended %d to cache", c, found, air_added); outLog(msg+", in "+getElapTimeStg(tm.elapsed())); progress.hide(); return false; }
void GlanceShower::Start () { if (!TabWidget_) { qWarning () << Q_FUNC_INFO << "no tab widget set"; return; } const int count = TabWidget_->count (); if (count < 2) { emit finished (true); return; } QAnimationGroup *animGroup = new QParallelAnimationGroup; const int sqr = std::sqrt ((double)count); int rows = sqr; int cols = sqr; if (rows * cols < count) ++cols; if (rows * cols < count) ++rows; const QRect& screenGeom = QApplication::desktop ()-> screenGeometry (Core::Instance ().GetReallyMainWindow ()); const int width = screenGeom.width (); const int height = screenGeom.height (); const int singleW = width / cols; const int singleH = height / rows; const int wW = singleW * 4 / 5; const int wH = singleH * 4 / 5; qreal scaleFactor = 0; QSize sSize; const int animLength = 400; QProgressDialog pg; pg.setMinimumDuration (1000); pg.setRange (0, count); for (int row = 0; row < rows; ++row) for (int column = 0; column < cols && column + row * cols < count; ++column) { const int idx = column + row * cols; pg.setValue (idx); QWidget *w = TabWidget_->widget (idx); if (!sSize.isValid ()) sSize = w->size () / 2; if (sSize != w->size ()) w->resize (sSize * 2); if (std::fabs (scaleFactor) < std::numeric_limits<qreal>::epsilon ()) scaleFactor = std::min (static_cast<qreal> (wW) / sSize.width (), static_cast<qreal> (wH) / sSize.height ()); QPixmap pixmap (sSize * 2); w->render (&pixmap); pixmap = pixmap.scaled (sSize, Qt::IgnoreAspectRatio, Qt::SmoothTransformation); { QPainter p (&pixmap); QPen pen (Qt::black); pen.setWidth (2 / scaleFactor + 1); p.setPen (pen); p.drawRect (QRect (QPoint (0, 0), sSize)); } GlanceItem *item = new GlanceItem (pixmap); item->SetIndex (idx); connect (item, SIGNAL (clicked (int)), this, SLOT (handleClicked (int))); Scene_->addItem (item); item->setTransformOriginPoint (sSize.width () / 2, sSize.height () / 2); item->setScale (scaleFactor); item->SetIdealScale (scaleFactor); item->setOpacity (0); item->moveBy (column * singleW, row * singleH); QAnimationGroup *pair = new QParallelAnimationGroup; QPropertyAnimation *posAnim = new QPropertyAnimation (item, "Pos"); posAnim->setDuration (animLength); posAnim->setStartValue (QPointF (0, 0)); posAnim->setEndValue (QPointF (column * singleW, row * singleH)); posAnim->setEasingCurve (QEasingCurve::OutSine); pair->addAnimation (posAnim); QPropertyAnimation *opacityAnim = new QPropertyAnimation (item, "Opacity"); opacityAnim->setDuration (animLength); opacityAnim->setStartValue (0.); opacityAnim->setEndValue (1.); pair->addAnimation (opacityAnim); animGroup->addAnimation (pair); } setScene (Scene_); setGeometry (screenGeom); animGroup->start (); Q_FOREACH (QGraphicsItem* item, items ()) { GlanceItem *itm = qgraphicsitem_cast<GlanceItem*> (item); itm->SetItemList (items ()); }
int QgsImageWarper::warpFile( const QString& input, const QString& output, const QgsGeorefTransform &georefTransform, ResamplingMethod resampling, bool useZeroAsTrans, const QString& compression, const QString &projection, double destResX, double destResY ) { if ( !georefTransform.parametersInitialized() ) return false; CPLErr eErr; GDALDatasetH hSrcDS, hDstDS; GDALWarpOptions *psWarpOptions; if ( !openSrcDSAndGetWarpOpt( input, resampling, georefTransform.GDALTransformer(), hSrcDS, psWarpOptions ) ) { // TODO: be verbose about failures return false; } double adfGeoTransform[6]; int destPixels, destLines; eErr = GDALSuggestedWarpOutput( hSrcDS, georefTransform.GDALTransformer(), georefTransform.GDALTransformerArgs(), adfGeoTransform, &destPixels, &destLines ); if ( eErr != CE_None ) { GDALClose( hSrcDS ); GDALDestroyWarpOptions( psWarpOptions ); return false; } // If specified, override the suggested resolution with user values if ( destResX != 0.0 || destResY != 0.0 ) { // If only one scale has been specified, fill in the other from the GDAL suggestion if ( destResX == 0.0 ) destResX = adfGeoTransform[1]; if ( destResY == 0.0 ) destResY = adfGeoTransform[5]; // Make sure user-specified coordinate system has canonical orientation if ( destResX < 0.0 ) destResX = -destResX; if ( destResY > 0.0 ) destResY = -destResY; // Assert that the north-up convention is fullfiled by GDALSuggestedWarpOutput (should always be the case) assert( adfGeoTransform[0] > 0.0 ); assert( adfGeoTransform[5] < 0.0 ); // Find suggested output image extent (in georeferenced units) double minX = adfGeoTransform[0]; double maxX = adfGeoTransform[0] + adfGeoTransform[1] * destPixels; double maxY = adfGeoTransform[3]; double minY = adfGeoTransform[3] + adfGeoTransform[5] * destLines; // Update line and pixel count to match extent at user-specified resolution destPixels = ( int )((( maxX - minX ) / destResX ) + 0.5 ); destLines = ( int )((( minY - maxY ) / destResY ) + 0.5 ); adfGeoTransform[0] = minX; adfGeoTransform[3] = maxY; adfGeoTransform[1] = destResX; adfGeoTransform[5] = destResY; } if ( !createDestinationDataset( output, hSrcDS, hDstDS, destPixels, destLines, adfGeoTransform, useZeroAsTrans, compression, projection ) ) { GDALClose( hSrcDS ); GDALDestroyWarpOptions( psWarpOptions ); return false; } // Create a QT progress dialog QProgressDialog *progressDialog = new QProgressDialog( mParent ); progressDialog->setWindowTitle( tr( "Progress indication" ) ); progressDialog->setRange( 0, 100 ); progressDialog->setAutoClose( true ); progressDialog->setModal( true ); progressDialog->setMinimumDuration( 0 ); // Set GDAL callbacks for the progress dialog psWarpOptions->pProgressArg = createWarpProgressArg( progressDialog ); psWarpOptions->pfnProgress = updateWarpProgress; psWarpOptions->hSrcDS = hSrcDS; psWarpOptions->hDstDS = hDstDS; // Create a transformer which transforms from source to destination pixels (and vice versa) psWarpOptions->pfnTransformer = GeoToPixelTransform; psWarpOptions->pTransformerArg = addGeoToPixelTransform( georefTransform.GDALTransformer(), georefTransform.GDALTransformerArgs(), adfGeoTransform ); // Initialize and execute the warp operation. GDALWarpOperation oOperation; oOperation.Initialize( psWarpOptions ); progressDialog->show(); progressDialog->raise(); progressDialog->activateWindow(); eErr = oOperation.ChunkAndWarpImage( 0, 0, destPixels, destLines ); // eErr = oOperation.ChunkAndWarpMulti(0, 0, destPixels, destLines); destroyGeoToPixelTransform( psWarpOptions->pTransformerArg ); GDALDestroyWarpOptions( psWarpOptions ); delete progressDialog; GDALClose( hSrcDS ); GDALClose( hDstDS ); return mWarpCanceled ? -1 : eErr == CE_None ? 1 : 0; }
bool AircraftData::import(QProgressDialog &progress, MainObject *mainObject){ int c = 0; int found = 0; progress.setRange(0, 2000); progress.setWindowTitle("Scanning Aircraft Directories"); progress.show(); progress.repaint(); //= Cache File QFile cacheFile( mainObject->data_file("aircraft.txt") ); if(!cacheFile.open(QIODevice::WriteOnly | QIODevice::Text)){ //qDebug() << "TODO Open error cachce file="; return true; } QTextStream out(&cacheFile); //= Get files Entries from Aircaft/ directory QDir aircraftDir( mainObject->X->aircraft_path() ); aircraftDir.setFilter( QDir::Dirs | QDir::NoSymLinks | QDir::NoDotAndDotDot); QStringList entries = aircraftDir.entryList(); progress.setRange(0, entries.size() + 20); for( QStringList::ConstIterator entry=entries.begin(); entry!=entries.end(); ++entry ){ // Filter out default dir names, should be a QDir name filter? if (*entry != "Instruments" && *entry != "Instruments-3d" && *entry != "Generic") { progress.setValue(c); progress.setLabelText(*entry); progress.repaint(); //** get the List of *-set.xml files in dir QDir dir( mainObject->X->aircraft_path(*entry) ); QStringList filters; filters << "*-set.xml"; QStringList list_xml = dir.entryList(filters); if(list_xml.count() > 0){ // << Scan MOdels QString directory; QString description; QString author; QString fdm; QString xml_file; QString aero; //** Add Path Node directory = QString(*entry); //** Add Models for (int i = 0; i < list_xml.size(); ++i){ xml_file = QString(list_xml.at(i)); aero = QString(xml_file); aero.chop(8); //*=parse the Xml file - f&*& long winded QString file_path = mainObject->X->aircraft_path(*entry); file_path.append("/"); file_path.append(list_xml.at(i)); QFile xmlFile( file_path); if (xmlFile.open(QIODevice::ReadOnly | QIODevice::Text)){ /* The file content is converted to UTF-8. Some files are Windows, encoding and throw error with QxmlQuery etc Its a hack and don't quite understand whats happening.. said pedro */ QString xmlString = QString(xmlFile.readAll()).toUtf8(); QXmlQuery query; query.setFocus(xmlString); //query.setFocus(&xmlFile); << Because file is not QTF8 using sting instead query.setQuery("PropertyList/sim"); if (query.isValid()){ QString res; query.evaluateTo(&res); xmlFile.close(); QDomDocument dom; dom.setContent("" + res + ""); QDomNodeList nodes = dom.elementsByTagName("sim"); QDomNode n = nodes.at(0); description = n.firstChildElement("description").text(); author = n.firstChildElement("author").text().trimmed().replace(("\n"),""); fdm = n.firstChildElement("flight-model").text(); } /* !query.isValid() */ } /* xmlFile.open() */ QStringList lines; lines << directory << aero << xml_file << description << fdm << author << file_path; out << lines.join("\t") << "\n"; found++; if(progress.wasCanceled()){ //qDebug() << "Progress cancelled!"; progress.hide(); return true; } c++; } } /* list_xml.count() > 0 */ } /* entry != INstruments etc */ } /* loop entries.() */ cacheFile.close(); return false; }
void SongsQueryWideget::export_excel_clicked() { ///建立临时表映射 /// setCursor(Qt::WaitCursor); QSqlQueryModel *sqlquery = new QSqlQueryModel(this); QSqlQuery _query; MediaPagingQuery argu; getQueryCondition(argu); if(!_sql->queryMedia_All(argu, _query)) return; sqlquery->setQuery(_query); int rows = sqlquery->rowCount(); int columns = sqlquery->columnCount(); setCursor(Qt::ArrowCursor); QString desktopPath = QProcessEnvironment::systemEnvironment().value("USERPROFILE")+"\\Desktop"; QString fileName = QFileDialog::getSaveFileName(tableView_songsQuery, "保存", //QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation), desktopPath, "Excel 文件(*.xls *.xlsx)"); QProgressDialog *progress = new QProgressDialog(this); progress->setLabelText("正在导出表格数据……"); progress->setRange(0, rows); progress->setModal(true); progress->setCancelButtonText("取消"); // progress->setMinimumSize(300, 50); progress->setMinimumWidth(400); progress->setAutoClose(true); if (fileName!="") { QAxObject *excel = new QAxObject; if (excel->setControl("Excel.Application")) //连接Excel控件 { excel->dynamicCall("SetVisible (bool Visible)","false");//不显示窗体 excel->setProperty("DisplayAlerts", false);//不显示任何警告信息。如果为true那么在关闭是会出现类似“文件已修改,是否保存”的提示 QAxObject *workbooks = excel->querySubObject("WorkBooks");//获取工作簿集合 workbooks->dynamicCall("Add");//新建一个工作簿 QAxObject *workbook = excel->querySubObject("ActiveWorkBook");//获取当前工作簿 QAxObject *worksheet = workbook->querySubObject("Worksheets(int)", 1); // //数据区 for(int i=0; i<rows; i++) { for (int j=0;j<columns; j++) { QModelIndex index = sqlquery->index(i, j); QString text = index.data().toString(); // table->item(i,j)?table->item(i,j)->text():"" worksheet->querySubObject("Cells(int,int)", i+1, j+1)->dynamicCall("SetValue(const QString&)", text); } QString label_text = QString("正在导出%1行……").arg(i+1); progress->setLabelText(label_text); progress->setValue(i+1); if(progress->wasCanceled()) { break; } } workbook->dynamicCall("SaveAs(const QString&)",QDir::toNativeSeparators(fileName));//保存至fileName workbook->dynamicCall("Close()");//关闭工作簿 //关闭excel excel->dynamicCall("Quit (void)"); delete excel; excel=NULL; QMessageBox box(QMessageBox::Question, "完成", "文件已经导出,是否现在打开?"); box.setStandardButtons(QMessageBox::Yes|QMessageBox::No); box.setButtonText(QMessageBox::Yes, "确定(&Q)"); box.setButtonText(QMessageBox::No, "取消(&C)"); if(box.exec() == QMessageBox::Yes) // if (QMessageBox::question(NULL,"完成","文件已经导出,是否现在打开?",QMessageBox::Yes|QMessageBox::No)==QMessageBox::Yes) { QString local_path = QString("file:///") + fileName; QDesktopServices::openUrl(QUrl(local_path, QUrl::TolerantMode)); //QDir::toNativeSeparators(fileName))); } } else { QMessageBox::warning(NULL,"错误","未能创建 Excel 对象,请安装 Microsoft Excel。",QMessageBox::Apply); } } // progress->close(); }