void MainWindow::OnImportNANDBackup() { auto response = QMessageBox::question( this, tr("Question"), tr("Merging a new NAND over your currently selected NAND will overwrite any channels " "and savegames that already exist. This process is not reversible, so it is " "recommended that you keep backups of both NANDs. Are you sure you want to " "continue?")); if (response == QMessageBox::No) return; QString file = QFileDialog::getOpenFileName(this, tr("Select the save file"), QDir::currentPath(), tr("BootMii NAND backup file (*.bin);;" "All Files (*)")); if (file.isEmpty()) return; QProgressDialog* dialog = new QProgressDialog(this); dialog->setMinimum(0); dialog->setMaximum(0); dialog->setLabelText(tr("Importing NAND backup")); dialog->setCancelButton(nullptr); auto beginning = QDateTime::currentDateTime().toMSecsSinceEpoch(); auto result = std::async(std::launch::async, [&] { DiscIO::NANDImporter().ImportNANDBin( file.toStdString(), [&dialog, beginning] { QueueOnObject(dialog, [&dialog, beginning] { dialog->setLabelText( tr("Importing NAND backup\n Time elapsed: %1s") .arg((QDateTime::currentDateTime().toMSecsSinceEpoch() - beginning) / 1000)); }); }, [this] { return RunOnObject(this, [this] { return QFileDialog::getOpenFileName(this, tr("Select the keys file (OTP/SEEPROM dump)"), QDir::currentPath(), tr("BootMii keys file (*.bin);;" "All Files (*)")) .toStdString(); }); }); QueueOnObject(dialog, &QProgressDialog::close); }); dialog->exec(); result.wait(); m_menu_bar->UpdateToolsMenu(Core::IsRunning()); }
void FilesystemWidget::CheckIntegrity(const DiscIO::Partition& partition) { QProgressDialog* dialog = new QProgressDialog(this); std::future<bool> is_valid = std::async( std::launch::async, [this, partition] { return m_volume->CheckIntegrity(partition); }); dialog->setLabelText(tr("Verifying integrity of partition...")); dialog->setWindowFlags(dialog->windowFlags() & ~Qt::WindowContextHelpButtonHint); dialog->setWindowTitle(tr("Verifying partition")); dialog->setMinimum(0); dialog->setMaximum(0); dialog->show(); while (is_valid.wait_for(std::chrono::milliseconds(50)) != std::future_status::ready) QCoreApplication::processEvents(); dialog->close(); if (is_valid.get()) QMessageBox::information(nullptr, tr("Success"), tr("Integrity check completed. No errors have been found.")); else QMessageBox::critical(nullptr, tr("Error"), tr("Integrity check for partition failed. The disc image is most " "likely corrupted or has been patched incorrectly.")); }
void test01(){ // Prepare the vector. QVector<int> vector; for (int i = 0; i < iterations; ++i) vector.append(i); // Create a progress dialog. QProgressDialog dialog; dialog.setLabelText(QString("Progressing using %1 thread(s)...").arg(QThread::idealThreadCount())); // Create a QFutureWatcher and connect signals and slots. QFutureWatcher<void> futureWatcher; QObject::connect(&futureWatcher, SIGNAL(finished()), &dialog, SLOT(reset())); QObject::connect(&dialog, SIGNAL(canceled()), &futureWatcher, SLOT(cancel())); QObject::connect(&futureWatcher, SIGNAL(progressRangeChanged(int,int)), &dialog, SLOT(setRange(int,int))); QObject::connect(&futureWatcher, SIGNAL(progressValueChanged(int)), &dialog, SLOT(setValue(int))); // Start the computation. futureWatcher.setFuture(QtConcurrent::map(vector, spin)); // Display the dialog and start the event loop. dialog.exec(); futureWatcher.waitForFinished(); // Query the future to check if was canceled. qDebug() << "Canceled?" << futureWatcher.future().isCanceled(); }
void FilesystemWidget::ExtractDirectory(const DiscIO::Partition& partition, const QString& path, const QString& out) { const DiscIO::FileSystem* filesystem = m_volume->GetFileSystem(partition); if (!filesystem) return; std::unique_ptr<DiscIO::FileInfo> info = filesystem->FindFileInfo(path.toStdString()); u32 size = info->GetTotalChildren(); QProgressDialog* dialog = new QProgressDialog(this); dialog->setMinimum(0); dialog->setMaximum(size); dialog->show(); bool all = path.isEmpty(); DiscIO::ExportDirectory( *m_volume, partition, *info, true, path.toStdString(), out.toStdString(), [all, dialog](const std::string& current) { dialog->setLabelText( (all ? QObject::tr("Extracting All Files...") : QObject::tr("Extracting Directory...")) .append(QStringLiteral(" %1").arg(QString::fromStdString(current)))); dialog->setValue(dialog->value() + 1); QCoreApplication::processEvents(); return dialog->wasCanceled(); }); dialog->close(); }
sqlqueryresultlist searchhandler::perform_grep(QString searchtxt, sqlqueryresultlist searchlist, bool exactmatch) { QVector<QString> strvec; sqlqueryresultlist resultlist; QFutureWatcher<sqlqueryresultlist> futureWatcher; QProgressDialog dialog; unsigned int n = searchlist.resultlist.size(); if (n == 0) return resultlist; strvec.resize(n); for (unsigned int i=0; i < n; i++) { strvec.replace(i, str2qt(searchlist.resultlist[i].filepath)); } dialog.setAutoReset(false); dialog.setLabelText(QString("Grep ").append(QString(tr("in progress"))).append(QString(" ..."))); dialog.setCancelButtonText(tr("Cancel")); QObject::connect(&futureWatcher, SIGNAL(finished()), &dialog, SLOT(reset())); QObject::connect(&dialog, SIGNAL(canceled()), &futureWatcher, SLOT(cancel())); QObject::connect(&futureWatcher, SIGNAL(progressRangeChanged(int,int)), &dialog, SLOT(setRange(int,int))); QObject::connect(&futureWatcher, SIGNAL(progressValueChanged(int)), &dialog, SLOT(setValue(int))); m_grepExactMatch = exactmatch; (*m_grepRegExp) = QRegExp(searchtxt.toAscii().data(), Qt::CaseInsensitive); m_grepRegExp->setPatternSyntax(QRegExp::RegExp2); futureWatcher.setFuture(QtConcurrent::mappedReduced(strvec, doGrep, collateGrep, QtConcurrent::SequentialReduce)); dialog.exec(); futureWatcher.waitForFinished(); if (futureWatcher.isCanceled() == false) resultlist = futureWatcher.result(); return resultlist; }
void UIMemoryEditor::on_pbSearchMemory_clicked() { UIMemorySearch memorySearch( this ); if (searchStartAddress == 0 && searchEndAddress == 0) { UIHexEditorWnd *hexEditorWnd=(UIHexEditorWnd *)saMemoryEditor->currentWidget(); searchStartAddress = hexEditorWnd->getStartAddress(); searchEndAddress = hexEditorWnd->getEndAddress(); } memorySearch.setParameters(searchType, searchString, searchStartAddress, searchEndAddress); if (memorySearch.exec() == QDialog::Accepted) { MemorySearch search( &memorySearch ); QProgressDialog progress; progress.setLabelText("Searching memory..."); connect(&search, SIGNAL(searchResult(bool, bool, u32)), this, SLOT(searchResult(bool, bool, u32))); connect(this, SIGNAL(killProgressDialog()), &progress, SLOT(accept())); connect(&progress, SIGNAL(canceled()), &search, SLOT(cancel())); connect(&search, SIGNAL(setBarValue(int)), &progress, SLOT(setValue(int))); connect(&search, SIGNAL(setBarRange(int, int)), &progress, SLOT(setRange(int, int))); search.start(); progress.exec(); }
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 Main_Window::on_sweep_clicked() { QProgressDialog *dlg = new QProgressDialog(this); dlg->setWindowModality(Qt::WindowModal); dlg->setLabelText("Frequency Sweep"); dlg->setCancelButtonText("Cancel"); dlg->setMaximum(100); dlg->show(); double start = ui.sweep_start->value(); double stop = ui.sweep_stop->value(); double step = ui.sweep_step->value(); for (double f = start; f <= stop && !dlg->wasCanceled(); f += step) { dlg->setValue((int)((f - start) * 100.0 / (stop - start))); QCoreApplication::processEvents(); ui.freq->setValue(f); on_idle_clicked(); update_freq(); send_freq(); on_cal_clicked(); on_tx_clicked(); usleep(100 * 1000); } delete dlg; }
/** * Saves the selected pictures. * First pops up a dialog box asking for the target dir. Then pops up * a progress dialog for feedback. */ void MainWindow::saveSelected() { /* Select target */ selectWorkDir(); /* Create a progress dialog */ QProgressDialog* progress = new QProgressDialog( i18n("Downloading ..."), i18n("Cancel"), 100, this, "progress", TRUE); progress->setCaption("Download"); connect(GPMessenger::instance(),SIGNAL(progressChanged(int)), progress,SLOT(setProgress(int))); progress->setAutoReset(false); progress->setAutoClose(false); progress->setProgress(0); KApplication::kApplication()->processEvents(); /* Download all pictures */ for (QIconViewItem *i = iconView->firstItem(); i && !progress->wasCancelled(); i = i->nextItem() ) { if (i->isSelected()) { /* Update progress dialog */ progress->setLabelText(i18n("Downloading ") + i->text() + "..."); /* Download picture */ GPInterface::downloadPicture(i->text(),"/"); } } progress->setProgress(100); delete progress; }
void ProgressDialog::updateProgress(float progress, const QString &stepString) { progressDialog->setValue(int(progress * 100)); QString message(stepString); if (message.length() > 33) message = message.left(17) + "..." + message.right(12); progressDialog->setLabelText(message); progressDialog->update(); qApp->processEvents(); }
void MainWindow::LoadFile() { if (FileFormatPluginList.size()) { QString FileName = QFileDialog::getOpenFileName(this, tr("Open File"), "", FileFormatPluginList[0]->getFormatDescription()); //test(); // Create a progress dialog. QProgressDialog dialog; dialog.setLabelText(QString("Загрузка данных из файла")); // Create a QFutureWatcher and connect signals and slots. QFutureWatcher<void> futureWatcher; QTimer timer; connect(&timer, SIGNAL(timeout()), this, SLOT(updateProgress())); timer.start(1000); QObject::connect(&futureWatcher, SIGNAL(finished()), &dialog, SLOT(reset())); QObject::connect(&dialog, SIGNAL(canceled()), SLOT(cancelOperation())); QObject::connect(&dialog, SIGNAL(canceled()), &futureWatcher, SLOT(cancel())); QObject::connect(this, SIGNAL(progressValueChanged(int)), &dialog, SLOT(setValue(int))); //extern void FileFormatPluginList[0]->getDataFromChannel(channel,(qint8*)data); QFuture<void> future = QtConcurrent::run(FileFormatPluginList[0], &FileReadInterface::LoadFile, FileName); // Start the computation. futureWatcher.setFuture(future); // Display the dialog and start the event loop. dialog.exec(); futureWatcher.waitForFinished(); dialog.setValue(100); dialog.hide(); timer.stop(); cube= FileFormatPluginList[0]->getCube(); QList<double> list = cube->GetListOfChannels(); foreach(double l , list) { ui->ChannelListWidget->addItem(QString("%1").arg(l)); }
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 MainWindow::openFile() { QString newFile = QFileDialog::getOpenFileName(this, tr("Open SQL File"), QDir::currentPath(), tr("SQL file (*.sql);;All Files (*)")); if (newFile.isNull()) return; QFile f(newFile); if (!f.open(QIODevice::ReadOnly | QIODevice::Text)) { QMessageBox::warning(this, tr("Open SQL Script"), tr("Cannot open file %1").arg(newFile)); return; } int prgTmp = 0; QProgressDialog * progress = new QProgressDialog(tr("Opening: %1").arg(newFile), tr("Abort"), 0, f.size(), this); connect(progress, SIGNAL(canceled()), this, SLOT(cancel())); progress->setWindowModality(Qt::WindowModal); progress->setMinimumDuration(1000); SqlViewWidget *newSqlview = new SqlViewWidget(); QFileInfo pathInfo(newFile); sqlViewWidget->addTab(newSqlview,pathInfo.fileName()); sqlViewWidget->setCurrentWidget(newSqlview); newSqlview->sqlInput->clear(); QTextStream in(&f); QString line; QStringList strList; while (!in.atEnd()) { line = in.readLine(); strList.append(line); prgTmp += line.length(); } f.close(); progress->setLabelText(tr("Formatting the text. Please wait.")); newSqlview->sqlInput->append(strList.join("\n")); newSqlview->sqlInput->setModified(false); delete progress; progress = 0; }
foreach(const QString &uid, uids) { // Progress cosmetics dlg.setLabelText(tr("Setting patient uuid %1 as current patient").arg(uid)); Utils::centerWidget(&dlg, this); qApp->processEvents(QEventLoop::ExcludeUserInputEvents); // Define current patient for extraction job.setPatientUid(uid); patient()->setCurrentPatientUid(uid); // Define output path QString fullname = patient()->data(Core::IPatient::FullName).toString(); QString dob = patient()->data(Core::IPatient::DateOfBirth).toString(); QString path = QString("%1/%2 %3") .arg(d->ui->pathChooser->path()) .arg(fullname) .arg(dob); if (!QDir().mkpath(path)) LOG_ERROR("Unable to create path: " + path); job.setOutputAbsolutePath(path); // Run extractors result << extractAll(extractors, job); Utils::Log::logTimeElapsed(chr, objectName(), QString("Extracted patient uid: %1").arg(uid)); // According to params -> recreate one big HTML file QString out, outCss; foreach(Core::PatientDataExtraction *exp, result) { // Append all secondary files into the master QString master; master = Utils::readTextFile(exp->masterAbsoluteFilePath(), Utils::DontWarnUser); QFile(exp->masterAbsoluteFilePath()).remove(); if (master.isEmpty()) continue; QString masterCss; masterCss = Utils::htmlTakeAllCssContent(master); master = Utils::htmlBodyContent(master); foreach(const QString &sec, exp->secondaryFiles()) { QString second = Utils::readTextFile(sec, Utils::DontWarnUser); QFile(sec).remove(); if (second.isEmpty()) continue; QString secCss; secCss = Utils::htmlTakeAllCssContent(second); master += Utils::htmlBodyContent(second); masterCss += secCss; } out += master; outCss += masterCss; }
void updateItemSiteLeadTimes::sUpdate() { ParameterList params; _warehouse->appendValue(params); _classCode->appendValue(params); XSqlQuery updateUpdate; QProgressDialog progress; progress.setWindowModality(Qt::ApplicationModal); MetaSQLQuery mql = mqlLoad("updateItemsiteLeadTimes", "load"); updateUpdate = mql.toQuery(params); if (ErrorReporter::error(QtCriticalMsg, this, tr("Error Loading Item Site Lead Times"), updateUpdate, __FILE__, __LINE__)) { return; } int count=0; progress.setMaximum(updateUpdate.size()); XSqlQuery update; while (updateUpdate.next()) { progress.setLabelText(tr("Site: %1\n" "Item: %2 - %3") .arg(updateUpdate.value("warehous_code").toString()) .arg(updateUpdate.value("item_number").toString()) .arg(updateUpdate.value("item_descrip1").toString())); ParameterList rparams = params; rparams.append("itemsite_id", updateUpdate.value("itemsite_id")); rparams.append("leadTimePad", _leadTimePad->value()); MetaSQLQuery mql2 = mqlLoad("updateItemsiteLeadTimes", "update"); update = mql2.toQuery(rparams); if (ErrorReporter::error(QtCriticalMsg, this, tr("Error Updating Item Site Lead Times"), update, __FILE__, __LINE__)) { return; } if (progress.wasCanceled()) break; count++; progress.setValue(count); } accept(); }
void SearchDialog::newSearch() { QString phrase = QInputDialog::getText(pgView, "Search in notebook", "Search phrase:", QLineEdit::Normal, lastPhrase); lastPhrase = phrase; if (phrase.isEmpty()) return; QProgressDialog *progress = new QProgressDialog(pgView); progress->setLabelText("Searching..."); progress->setCancelButton(0); progress->setMinimumDuration(500); progress->setValue(0); Search *search = new Search(pgView->notebook()); QList<SearchResult> res = search->immediatelyFindPhrase(phrase); if (res.isEmpty()) { delete progress; QMessageBox::information(pgView, "Search - eln", QString::fromUtf8("Search phrase “%1” not found") .arg(phrase)); return; } SearchResultScene *scene = new SearchResultScene(phrase, QString::fromUtf8("Search results for “%1”") .arg(phrase), res, pgView->notebook()->bookData()); scene->populate(); connect(scene, SIGNAL(pageNumberClicked(int, Qt::KeyboardModifiers, QString, QString)), this, SLOT(gotoPage(int, Qt::KeyboardModifiers, QString, QString))); SearchView *view = new SearchView(scene); view->setAttribute(Qt::WA_DeleteOnClose, true); connect(parent(), SIGNAL(destroyed()), view, SLOT(close())); delete progress; view->resize(pgView->size()*.9); QString ttl = pgView->notebook()->bookData()->title(); view->setWindowTitle("Search in: " + ttl.replace(QRegExp("\\s\\s*"), " ") + " - eln"); view->show(); }
void Demo::OpenDialog() { QProgressDialog* dialog = new QProgressDialog(this); dialog->setLabelText("Nyan nyan nyan nyan"); dialog->setWindowTitle("Nyan nyan nyan nyan"); dialog->setCancelButtonText("Nooooooooo!"); dialog->setMinimumWidth(350); QTimer* timer = new QTimer(dialog); timer->setInterval(100); connect(timer, SIGNAL(timeout()), SLOT(DialogTimerFired())); connect(dialog, SIGNAL(canceled()), dialog, SLOT(deleteLater())); dialog->show(); timer->start(); }
bool NXMAccessManager::loggedIn() const { if (m_LoginState == LOGIN_CHECKING) { QProgressDialog progress; progress.setLabelText(tr("Verifying Nexus login")); progress.show(); while (m_LoginState == LOGIN_CHECKING) { QCoreApplication::processEvents(); QThread::msleep(100); } progress.hide(); } return m_LoginState == LOGIN_VALID; }
void DatabaseWidget::readCsvBase(QString openFilename) { // QString currTime=QDateTime::currentDateTime().toString("dd.MM.yyyy hh:mm:ss.zzz"); // qDebug().noquote() << "readCsvBase BEGIN" // << currTime // << this->thread()->currentThreadId(); emit toDebug(objectName(), QString("Открывается файл '%1'.").arg(openFilename)); QString name = QFileInfo(openFilename).fileName(); if(!QFileInfo(openFilename).exists()) { emit toDebug(objectName(), QString("Файл '%1' не найден").arg(openFilename)); return; } QProgressDialog *dialog = new QProgressDialog; dialog->setWindowTitle(trUtf8("Обработка базы (1/3)")); dialog->setLabelText(trUtf8("Открывается файл \"%1\". \nОжидайте ...") .arg(name)); dialog->setCancelButtonText(trUtf8("Отмена")); QObject::connect(dialog, SIGNAL(canceled()), &_futureWatcher, SLOT(cancel())); QObject::connect(&_futureWatcher, SIGNAL(progressRangeChanged(int,int)), dialog, SLOT(setRange(int,int))); QObject::connect(&_futureWatcher, SIGNAL(progressValueChanged(int)), dialog, SLOT(setValue(int))); QObject::connect(&_futureWatcher, SIGNAL(finished()), dialog, SLOT(deleteLater())); QObject::connect(&_futureWatcher, SIGNAL(finished()), dialog, SLOT(hide())); QFuture<ListAddress> f1 = QtConcurrent::run( readFile, openFilename, MAX_OPEN_ROWS); // Start the computation. _futureWatcher.setFuture(f1); dialog->exec(); // currTime=QDateTime::currentDateTime().toString("dd.MM.yyyy hh:mm:ss.zzz"); // qDebug().noquote() << "readCsvBase END" // << currTime // << this->thread()->currentThreadId(); }
void DatabaseWidget::onProcessOfOpenFinished() { if(_futureWatcher.isFinished() && !_futureWatcher.isCanceled()) { _paddr.reset(new ListAddress(_futureWatcher.future().result())); emit toDebug(objectName(), QString("Открытие файла успешно завершено. Прочитано строк = %1") .arg(_paddr.data()->size())); if(!_paddr.data()->isEmpty()) { // QString currTime=QDateTime::currentDateTime().toString("dd.MM.yyyy hh:mm:ss.zzz"); // qDebug().noquote() << "onProcessOfOpenFinished BEGIN" // << currTime // << this->thread()->currentThreadId(); emit toDebug(objectName(), QString("Начало обработки прочитанной базы.")); QProgressDialog *dialog = new QProgressDialog; dialog->setWindowTitle(trUtf8("Обработка базы (2/3)")); dialog->setLabelText(trUtf8("Обрабатывается файл. Строк: \"%1\". \nОжидайте ...") .arg(_paddr.data()->size())); dialog->setCancelButtonText(trUtf8("Отмена")); QObject::connect(dialog, SIGNAL(canceled()), &_futureWatcherParser, SLOT(cancel())); QObject::connect(&_futureWatcherParser, SIGNAL(progressRangeChanged(int,int)), dialog, SLOT(setRange(int,int))); QObject::connect(&_futureWatcherParser, SIGNAL(progressValueChanged(int)), dialog, SLOT(setValue(int))); QObject::connect(&_futureWatcherParser, SIGNAL(finished()), dialog, SLOT(deleteLater())); QFuture<void> f1 = QtConcurrent::map(*_paddr, parsingAddress ); // Start the computation. _futureWatcherParser.setFuture(f1); dialog->exec(); // currTime=QDateTime::currentDateTime().toString("dd.MM.yyyy hh:mm:ss.zzz"); // qDebug().noquote() << "onProcessOfOpenFinished END" // << currTime // << this->thread()->currentThreadId(); }
bool MainWindow::parseDirectory(QString dirName, parseType type,bool convert,bool create,QProgressDialog &progress) { QFileInfoList list; QStringList filter; QDir dir(dirName); /* create filter list for files */ filter.append(QString("*.h")); filter.append(QString("*.c")); filter.append(QString("*.cpp")); filter.append(QString("*.cxx")); /* parse files in current directory */ list = dir.entryInfoList(filter,QDir::Files); progress.setMaximum(progress.maximum()+list.size()); for(int i = 0;i<list.size();i++) { /* increase progress bar */ progress.setValue(progress.value()+1); if(convert) { if(!parser.converteFile(list.at(i).absoluteFilePath())) return false; } else { if(!parser.parseFile(list.at(i).absoluteFilePath())) return false; } progress.setLabelText(list.at(i).absoluteFilePath()); } /* go recursive through all the subdiectories */ list = dir.entryInfoList(QDir::Dirs|QDir::NoDotAndDotDot); for(int i = 0;i<list.size();i++) { if(!parseDirectory(list.at(i).absoluteFilePath(),type,convert,create,progress)) return false; } return true; }
void createPlannedOrdersByPlannerCode::sCreate(ParameterList params) { XSqlQuery createCreate; QProgressDialog progress; progress.setWindowModality(Qt::ApplicationModal); MetaSQLQuery mql = mqlLoad("schedule", "load"); createCreate = mql.toQuery(params); if (createCreate.lastError().type() != QSqlError::NoError) { systemError(this, createCreate.lastError().databaseText(), __FILE__, __LINE__); return; } int count=0; progress.setMaximum(createCreate.size()); XSqlQuery create; while (createCreate.next()) { progress.setLabelText(tr("Site: %1\n" "Item: %2 - %3") .arg(createCreate.value("warehous_code").toString()) .arg(createCreate.value("item_number").toString()) .arg(createCreate.value("item_descrip1").toString())); ParameterList rparams = params; rparams.append("itemsite_id", createCreate.value("itemsite_id")); MetaSQLQuery mql2 = mqlLoad("schedule", "create"); create = mql2.toQuery(rparams); if (create.lastError().type() != QSqlError::NoError) { systemError(this, create.lastError().databaseText(), __FILE__, __LINE__); return; } if (progress.wasCanceled()) break; count++; progress.setValue(count); } accept(); }
void MVCrossCorrelogramsWidget::updateWidget() { if (d->m_path.isEmpty()) return; int k0=d->m_base_unit_num; DiskReadMda X; X.setPath(d->m_path); QProgressDialog dlg; dlg.show(); dlg.setLabelText("Loading cross correlograms..."); dlg.repaint(); qApp->processEvents(); QList<FloatList> data0=get_cross_correlogram_datas_2(X,k0); int K=data0.count()-1; int num_rows=(int)sqrt(K); if (num_rows<1) num_rows=1; int num_cols=(K+num_rows-1)/num_rows; d->m_num_columns=num_cols; QWidget *W=this; W->setAttribute(Qt::WA_DeleteOnClose); QGridLayout *GL=new QGridLayout; GL->setHorizontalSpacing(20); GL->setVerticalSpacing(0); GL->setMargin(0); W->setLayout(GL); for (int k1=1; k1<=K; k1++) { HistogramView *HV=new HistogramView; HV->setData(data0[k1]); HV->autoSetBins(50); int k2=k1; if (k0>=1) k2=k0; QString title0=QString("%1/%2").arg(k1).arg(k2); HV->setTitle(title0); GL->addWidget(HV,(k1-1)/num_cols,(k1-1)%num_cols); HV->setProperty("unit_number",k1); connect(HV,SIGNAL(clicked()),this,SLOT(slot_histogram_view_clicked())); connect(HV,SIGNAL(activated()),this,SLOT(slot_histogram_view_activated())); d->m_histogram_views << HV; } }
int main(int argc, char **argv) { QApplication app(argc, argv); QVector<int> vector; for (int i=0; i<iterations; ++i) vector.append(i); QProgressDialog dialog; dialog.setLabelText(QString("Progressing using %1 thraed(s)...").arg(QThread::idealThreadCount())); QFutureWatcher<void> futureWatcher; QObject::connect(&futureWatcher, SIGNAL(finished()), &dialog, SLOT(reset())); QObject::connect(&dialog, SIGNAL(canceled()), &futureWatcher, SLOT(cancel())); QObject::connect(&futureWatcher, SIGNAL(progressRangeChanged(int, int)), &dialog, SLOT(setRange(int, int))); QObject::connect(&futureWatcher, SIGNAL(progressValueChanged(int)), &dialog, SLOT(setValue(int))); futureWatcher.setFuture(QtConcurrent::map(vector, spin)); dialog.exec(); futureWatcher.waitForFinished(); qDebug() << "Canceled ?" << futureWatcher.future().isCanceled(); }
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 Polar::setPolarName(QString fname) { isCsv=true; loaded=false; clearPolar(); if(this->mainWindow->getSelectedBoat() && this->mainWindow->getSelectedBoat()->get_boatType()==BOAT_REAL) coeffPolar=Settings::getSetting("polarEfficiency",100).toInt()/100.0; else coeffPolar=1.0; //qWarning() << "Opening polar" << fname<<"with coeff"<<coeffPolar; name=fname; QString nameF = appFolder.value("polar")+fname+".csv"; QFile file(nameF); if (fname.endsWith(".csv",Qt::CaseInsensitive) || fname.endsWith(".pol",Qt::CaseInsensitive)) { nameF=appFolder.value("polar")+fname; file.setFileName(nameF); if (!file.open(QIODevice::ReadOnly | QIODevice::Text )) { QMessageBox::warning(0,QObject::tr("Lecture de polaire"), QString(QObject::tr("Impossible d'ouvrir le fichier %1")).arg(name)); return; } isCsv=fname.endsWith("csv",Qt::CaseInsensitive); } else { if (!file.open(QIODevice::ReadOnly | QIODevice::Text )) { isCsv=false; nameF = appFolder.value("polar")+fname+".pol"; file.setFileName(nameF); if (!file.open(QIODevice::ReadOnly | QIODevice::Text )) { QMessageBox::warning(0,QObject::tr("Lecture de polaire"), QString(QObject::tr("Impossible d'ouvrir le fichier %1 (ni en .csv ni en .pol)")).arg(name)); return; } } } QTextStream stream(&file); QString line; QStringList list; /* read first line to see line length */ line=stream.readLine(); line.remove("\""); if(line.isNull()) { QMessageBox::warning(0,QObject::tr("Lecture de polaire"), QString(QObject::tr("Fichier %1 vide")).arg(fname)); file.close(); return; } if(isCsv) list = line.split(';'); else list = line.split('\t'); if(list[0].toUpper() != "TWA\\TWS" && list[0].toUpper() != "TWA/TWS" && list[0].toUpper() != "TWA") { QMessageBox::warning(0,QObject::tr("Lecture de polaire"), QString(QObject::tr("Fichier %1 invalide (doit commencer par TWA\\TWS et non '%2')")) .arg(fname) .arg(list[0])); file.close(); return; } int i; for(i=1;i<list.count();++i) { if(!tws.isEmpty() && list[i].toDouble()<=tws.last()) break; tws.append(list[i].toDouble()); } bool missingTws0=false; if(tws.first()!=0.0) { missingTws0=true; } bool firstTWA=true; while(true) { line=stream.readLine(); if(line.isNull()) break; line.remove("\""); if (isCsv) list = line.split(";"); else list = line.split("\t"); if(firstTWA) { firstTWA=false; if(list.first().toDouble()!=0.0) { for(int t=0;t<tws.count();++t) { polar_data.append(0); } if(missingTws0) polar_data.append(0); twa.append(0.0); } } twa.append(list[0].toDouble()); if(missingTws0) polar_data.append(0); for(i=1;i<list.count();++i) { if(i>tws.count()) break; polar_data.append(list[i].toDouble()*this->coeffPolar); } while(i<=tws.count()) polar_data.append(0); } if(missingTws0) tws.prepend(0.0); #if 0 qWarning()<<"polar data for"<<nameF; QString debug="xxx.x "; foreach(double dd,tws) debug+=QString().sprintf("%04.1f ",dd); qWarning()<<debug; QListIterator<double> i1(polar_data); QListIterator<double> i2(twa); while(i2.hasNext()) { debug=QString().sprintf("%05.1f ",i2.next()); for(int nn=0;nn<tws.count();++nn) debug+=QString().sprintf("%04.1f ",i1.next()); qWarning()<<debug; } #endif mid_twa=qRound(twa.count()/2.0); mid_tws=qRound(tws.count()/2.0); /* polaire chargee */ /* pre-calculate B-VMG for every tws at 0.1 precision with a twa step of 1 and then .1 */ double ws=0.0; double wa=0.0; double bvmg,bvmg_d,bvmg_u,wa_u,wa_d,wa_limit; maxSpeed=0.0; do { wa_u=0.0; wa_d=180.0; bvmg_u=bvmg_d=0; double speed; do { speed=myGetSpeed(ws,wa,true); if(speed>maxSpeed) maxSpeed=speed; bvmg=speed*cos(degToRad(wa)); if(bvmg_u<bvmg) //bvmg is positive here { bvmg_u=bvmg; wa_u=wa; } if(bvmg_d>bvmg) //bvmg is negative here { bvmg_d=bvmg; wa_d=wa; } wa=qRound(wa+1); } while(wa<181.00); wa=wa_u-1; wa_limit=wa_u+1; if(wa<0) wa=0.0; if(wa_limit<1) wa_limit=1.0; if(wa_limit>180) wa_limit=180.0; bvmg_u=0.0; do { speed=myGetSpeed(ws,wa,true); if(speed>maxSpeed) maxSpeed=speed; bvmg=speed*cos(degToRad(wa)); if(bvmg_u<bvmg) { bvmg_u=bvmg; wa_u=wa; } wa=wa+0.1; } while(wa<(wa_limit+0.1000)); wa=wa_d-1; wa_limit=wa_d+1; if(wa<0) wa=0.0; if(wa_limit<1) wa_limit=1.0; if(wa_limit>180) wa_limit=180.0; bvmg_d=0.0; do { speed=myGetSpeed(ws,wa,true); if(speed>maxSpeed) maxSpeed=speed; bvmg=speed*cos(degToRad(wa)); if(bvmg_d>bvmg) { bvmg_d=bvmg; wa_d=wa; } wa=wa+0.1; }while(wa<wa_limit+0.1); best_vmg_up.append(wa_u); best_vmg_down.append(wa_d); wa=0.0; ws=ws+.1; }while(ws<60.1); loaded=true; QFileInfo fi(file.fileName()); QString nameFVmg = appFolder.value("polar")+fi.baseName()+".vmg"; fileVMG.setFileName(nameFVmg); if (fileVMG.open(QIODevice::ReadOnly | QIODevice::Text )) { if(fileVMG.size()<4329500 || fileVMG.size()>4329700) fileVMG.remove(); else { QFileInfo info1(fileVMG); QFileInfo info2(file); if(this->mainWindow->isStartingUp && info1.lastModified()<info2.lastModified()) fileVMG.remove(); else { file.close(); return; } } } file.close(); //precalculate regular VMGs //qWarning() << "Start computing vmg"; fileVMG.open(QIODevice::WriteOnly | QIODevice::Text ); double vmg=0; QTextStream sVmg(&fileVMG); QString ssVmg; QProgressDialog * progress; progress=new QProgressDialog((QWidget*)mainWindow); progress->setWindowModality(Qt::ApplicationModal); progress->setLabelText(tr("Pre-calcul des valeurs de VMG pour ")+fname); progress->setMaximum(600); progress->setMinimum(0); progress->setCancelButton(NULL); progress->setMaximumHeight(100); progress->show(); for (int tws=0;tws<601;tws++) { progress->setValue(tws); for (int twa=0;twa<1801;twa++) { bvmgWind((double) twa/10.0,(double) tws/10.0,&vmg); ssVmg.sprintf("%.4d",qRound(A360(vmg)*10.0)); sVmg<<ssVmg; } } fileVMG.close(); if(!fileVMG.open(QIODevice::ReadOnly | QIODevice::Text )) qWarning()<<"fileVMG could not be re-opened!"; progress->close(); delete progress; }
void FLUtil::setLabelText(const QString &l, const QString &id) { QProgressDialog *pd = dictProgressD_.find(id); if (pd) pd->setLabelText(l); }
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 CSVToolWindow::importStart() { QString mapname = atlasWindow()->map(); CSVAtlas *atlas = _atlasWindow->getAtlas(); if (mapname.isEmpty()) { QStringList mList = atlas->mapList(); if(mList.isEmpty()) { _msghandler->message(QtWarningMsg, tr("No Maps Loaded"), tr("<p>There are no maps loaded to select from. " "Either load an atlas that contains maps or " "create a new one before continuing.")); return false; } mList.sort(); bool valid; mapname = QInputDialog::getItem(this, tr("Select Map"), tr("Select Map:"), mList, 0, false, &valid); if (!valid) return false; } CSVMap map = atlas->map(mapname); map.simplify(); QList<CSVMapField> fields = map.fields(); if (map.name() != mapname || fields.isEmpty()) { _msghandler->message(QtWarningMsg, tr("Invalid Map"), tr("<p>The selected map does not appear to be valid.")); return false; } CSVMap::Action action = map.action(); if (action != CSVMap::Insert) { _msghandler->message(QtWarningMsg, tr("Action not implemented"), tr("<p>The action %1 for this map is not supported.") .arg(CSVMap::actionToName(action))); return false; } if (!_data || _data->rows() < 1) { _msghandler->message(QtWarningMsg, tr("No data"), tr("<p>There are no data to process. " "Load a CSV file before continuing.")); return false; } int total = _data->rows(); int current = 0, error = 0, ignored = 0; if (! _log) _log = new LogWindow(this); if(usetransaction) QSqlQuery begin("BEGIN;"); QString errMsg; if(!map.sqlPre().trimmed().isEmpty()) { if(usetransaction) QSqlQuery savepoint("SAVEPOINT presql;"); QSqlQuery pre; if(!pre.exec(map.sqlPre())) { errMsg = QString("ERROR Running Pre SQL query: %1").arg(pre.lastError().text()); _log->_log->append("\n\n----------------------\n"); _log->_log->append(errMsg); _log->show(); _log->raise(); if(map.sqlPreContinueOnError()) { _log->_log->append(tr("\n\nContinuing with rest of import\n\n")); if(usetransaction) QSqlQuery sprollback("ROLLBACK TO SAVEPOINT presql;"); if(usetransaction) QSqlQuery savepoint("RELEASE SAVEPOINT presql;"); } else { if(usetransaction) QSqlQuery rollback("ROLLBACK;"); _msghandler->message(QtWarningMsg, tr("Error"), tr("<p>There was an error running the Pre SQL " "query. " "Aborting transaction." "\n\n----------------------\n%1").arg(errMsg)); return false; } } } QString progresstext(tr("Importing %1: %2 rows out of %3")); int expected = total; QProgressDialog *progress = new QProgressDialog(progresstext .arg(map.name()).arg(0).arg(expected), tr("Cancel"), 0, expected, this); progress->setWindowModality(Qt::WindowModal); bool userCanceled = false; QString query; QString front; QString back; QString value; QString label; QVariant var; QStringList errorList; for(current = 0; current < total; ++current) { if(usetransaction) QSqlQuery savepoint("SAVEPOINT csvinsert;"); if(action == CSVMap::Insert) { query = QString("INSERT INTO %1 ").arg(map.table()); front = "("; back = " VALUES("; QList<CSVMapField> fields = map.fields(); QMap<QString,QVariant> values; for (int i = 0; i < fields.size(); i++) { switch(fields.at(i).action()) { case CSVMapField::Action_UseColumn: { value = _data->value(current, fields.at(i).column()-1); if(value.isNull()) { switch (fields.at(i).ifNullAction()) { case CSVMapField::UseDefault: continue; case CSVMapField::UseEmptyString: { var = QVariant(QString("")); break; } case CSVMapField::UseAlternateValue: { var = QVariant(fields.at(i).valueAlt()); break; } case CSVMapField::UseAlternateColumn: { value = _data->value(current, fields.at(i).columnAlt()-1); if(value.isNull()) { switch (fields.at(i).ifNullActionAlt()) { case CSVMapField::UseDefault: continue; case CSVMapField::UseEmptyString: { var = QVariant(QString("")); break; } case CSVMapField::UseAlternateValue: { var = QVariant(fields.at(i).valueAlt()); break; } default: // Nothing var = QVariant(QString::null); } } else var = QVariant(value); break; } default: // Nothing var = QVariant(QString::null); } } else var = QVariant(value); break; } case CSVMapField::Action_UseEmptyString: { var = QVariant(QString("")); break; } case CSVMapField::Action_UseAlternateValue: { var = QVariant(fields.at(i).valueAlt()); break; } case CSVMapField::Action_UseNull: { var = QVariant(QString::null); break; } default: continue; } label = ":" + fields.at(i).name(); if(!values.empty()) { front += ", "; back += ", "; } values.insert(label, var); front += fields.at(i).name(); back += label; } if(values.empty()) { ignored++; errMsg = QString("IGNORED Record %1: There are no columns to insert").arg(current+1); errorList.append(errMsg); continue; } front += ") "; back += ")"; query += front + back; QSqlQuery qry; qry.prepare(query); QMap<QString,QVariant>::iterator vit; for(vit = values.begin(); vit != values.end(); ++vit) qry.bindValue(vit.key(), vit.value()); if(!qry.exec()) { if(usetransaction) QSqlQuery sprollback("ROLLBACK TO SAVEPOINT csvinsert;"); error++; errMsg = QString("ERROR Record %1: %2").arg(current+1).arg(qry.lastError().text()); errorList.append(errMsg); } } if (progress->wasCanceled()) { userCanceled = true; break; } if(! (current % 1000)) { progress->setLabelText(progresstext.arg(map.name()).arg(current).arg(expected)); progress->setValue(current); } } progress->setValue(total); if (error || ignored || userCanceled) { _log->_log->append(tr("Map: %1\n" "Table: %2\n" "Method: %3\n\n" "Total Records: %4\n" "# Processed: %5\n" "# Ignored: %6\n" "# Errors: %7\n\n") .arg(map.name()).arg(map.table()) .arg(CSVMap::actionToName(map.action())) .arg(total).arg(current).arg(ignored).arg(error)); _log->_log->append(errMsg); _log->_log->append(errorList.join("\n")); _log->show(); _log->raise(); if (_msghandler && // log messages there's a non-interactive message handler qobject_cast<XAbstractMessageHandler*>(_msghandler) && ! qobject_cast<InteractiveMessageHandler*>(_msghandler)) _msghandler->message(error ? QtCriticalMsg : QtWarningMsg, tr("Import Processing Status"), _log->_log->toPlainText()); } if (! userCanceled && ! map.sqlPost().trimmed().isEmpty()) { QSqlQuery post; if(!post.exec(map.sqlPost())) { errMsg = QString("ERROR Running Post SQL query: %1").arg(post.lastError().text()); _log->_log->append("\n\n----------------------\n"); _log->_log->append(errMsg); _log->show(); _log->raise(); if(usetransaction) QSqlQuery rollback("ROLLBACK;"); _msghandler->message(QtCriticalMsg, tr("Error"), tr("<p>There was an error running the post sql " "query and changes were rolled back. " "\n\n----------------------\n%1").arg(errMsg)); return false; } } if (userCanceled) { if(usetransaction) QSqlQuery rollback("ROLLBACK;"); _log->_log->append(tr("\n\nImport canceled by user. Changes were rolled back.")); return false; } if(usetransaction) QSqlQuery commit("COMMIT"); if (! error) { _msghandler->message(QtDebugMsg, tr("Import Complete"), tr("The import of %1 completed successfully.") .arg(_currentDir)); return true; } return false; }