void CandidateIndexesPage::generateCandidates() { if (generator != nullptr) { return; } MainWizard *mainWizard = static_cast<MainWizard*>(wizard()); QProgressDialog *progress = new QProgressDialog( tr("Generating candidates..."), tr("Cancel"), 0, 100, this ); progress->setModal(true); progress->setValue(0); progress->setMinimumDuration(0); generator = new GenerateCandidateIndexes(mainWizard->project); connect(generator, SIGNAL(finished()), progress, SLOT(accept())); connect(generator, SIGNAL(progress(int)), progress, SLOT(setValue(int))); connect(generator, SIGNAL(resultReady()), this, SLOT(candidatesGenerated())); connect(progress, SIGNAL(canceled()), generator, SLOT(terminate())); generator->start(); }
/*========================================================================= doFileSearch =========================================================================*/ void MainWindow::doFileSearch (const QString &path, const QString &text, KFileList *fileList) { QProgressDialog progress (tr("Searching..."), tr("Stop"), 0, 100, this); progress.setWindowModality (Qt::WindowModal); progress.setMinimumDuration (0); progress.show(); _doFileSearch (path, "", text, fileList, progress); progress.setValue (100); }
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; }
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 LibraryView::deleteSongs(){ QSet<library_song_id_t> selectedIds = Utils::getSelectedIds<library_song_id_t>( this, libraryModel, DataStore::getLibIdColName(), proxyModel); QProgressDialog *deletingProgress = new QProgressDialog(tr("Deleting Songs..."), tr("Cancel"), 0, selectedIds.size()*2, this); deletingProgress->setWindowModality(Qt::WindowModal); deletingProgress->setMinimumDuration(250); dataStore->removeSongsFromLibrary(selectedIds, deletingProgress); if(!deletingProgress->wasCanceled()){ emit libNeedsSync(); } deletingProgress->close(); }
void MetaWindow::addMediaSources(const QList<Phonon::MediaSource>& musicToAdd){ if(musicToAdd.isEmpty()){ QMessageBox::information( this, "No Music Found", "Sorry, but we couldn't find any new music that we know how to play."); return; } int numNewFiles = musicToAdd.size(); QProgressDialog *addingProgress = new QProgressDialog( "Loading Library...", "Cancel", 0, numNewFiles, this); addingProgress->setWindowModality(Qt::WindowModal); addingProgress->setMinimumDuration(250); dataStore->addMusicToLibrary(musicToAdd, addingProgress); if(!addingProgress->wasCanceled()){ syncLibrary(); } addingProgress->close(); }
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; }
void AM1DCalibrationABEditor::onApplyToOtherScansChosen() { disconnect(chooseScanDialog_, SIGNAL(accepted()), this, SLOT(onApplyToOtherScansChosen())); QList<QUrl> scans = chooseScanDialog_->getSelectedScans(); chooseScanDialog_->clearSelection(); if(scans.isEmpty()) { chooseScanDialog_->close(); return; } QProgressDialog* progressDialog = new QProgressDialog(QString("Applying analysis parameters to %1 scans...").arg(scans.count()), "Stop", 0, scans.count(), chooseScanDialog_); progressDialog->setMinimumDuration(0); int scansModified = 0; for(int s=0; s<scans.count(); ++s) { progressDialog->setValue(s); QUrl scanUrl = scans.at(s); bool isScanning; QString scanName; AMScan* scan = AMScan::createFromDatabaseUrl(scanUrl, false, &isScanning, &scanName); if(isScanning) { AMErrorMon::alert(this, -333, QString("Batch calibrating: Cannot apply calibration parameters to scan '%1' because it's still acquiring data.").arg(scanName)); continue; } if(!scan) { AMErrorMon::alert(this, -334, QString("Batch calibrating: Could not open the scan at '%1'. This looks like a problem in the database; please report this problem to the REIXS Acquaman developers.").arg(scanUrl.toString())); continue; } bool calibrationABFound = false; for(int i=0, cc=scan->analyzedDataSourceCount(); i<cc; ++i) { AM1DCalibrationAB* CalibrationAB = qobject_cast<AM1DCalibrationAB*>(scan->analyzedDataSources()->at(i)); if(CalibrationAB) { calibrationABFound = true; CalibrationAB->setEnergyCalibrationOffset(analysisBlock_->energyCalibrationOffset()); CalibrationAB->setEnergyCalibrationReference(analysisBlock_->energyCalibrationReference()); CalibrationAB->setEnergyCalibrationScaling(analysisBlock_->energyCalibrationScaling()); CalibrationAB->setToEdgeJump(analysisBlock_->toEdgeJump()); CalibrationAB->setPreEdgePoint(analysisBlock_->preEdgePoint()); CalibrationAB->setPostEdgePoint(analysisBlock_->postEdgePoint()); } } if(!calibrationABFound) { AMErrorMon::alert(this, -335, QString("Batch calibrating: Could not find a calibration tool in the scan '%1'").arg(scan->fullName())); } else { scansModified++; scan->storeToDb(scan->database()); } scan->deleteLater(); // delete scan. } progressDialog->setValue(scans.count()); progressDialog->deleteLater(); AMErrorMon::information(this, 0, QString("Batch Calibrating: set the calibration parameters successfully for %1 XAS scans.").arg(scansModified)); chooseScanDialog_->close(); }
/*========================================================================= copyFromClipboard =========================================================================*/ bool KFileBrowser::copyFromClipboard (const FileClipboard *fc) { bool ret = FALSE; const QStringList &names = fc->getNames(); const QString &root = fc->getRoot(); int l = names.count(); int filesDone = 0; int dirsDone = 0; QProgressDialog progress (tr("Copying files..."), tr("Stop"), 0, l, this); progress.setWindowModality (Qt::WindowModal); progress.setMinimumDuration (0); progress.show(); bool stop = false; QString errorMessage = ""; for (int i = 0; i < l && !progress.wasCanceled() &&!stop; i++) { QString sourceName = root + "/" + names[i]; QString targetName; if (fc->getPasteByNameOnly()) { QFileInfo info (path + "/" + names[i]); QString shortName = info.fileName(); targetName = path + "/" + shortName; } else targetName = path + "/" + names[i]; errorMessage = ""; if (sourceName == targetName) { errorMessage = tr ("Source and destination files are the same"); } else { QFileInfo info (sourceName); if (info.isDir()) { QDir dir; if (dir.mkpath (targetName)) dirsDone++; else errorMessage = tr ("Can't create folder") + " " + targetName; } else { bool doCopy = false; QFile targetFile (targetName); QFile sourceFile (sourceName); if (targetFile.exists()) { QMessageBox msgBox; msgBox.setText(tr("File exists")); msgBox.setInformativeText (errorMessage + ". " + tr("Do you want to overwrite file") + " " + targetName + "?"); msgBox.setStandardButtons(QMessageBox::Ok | QMessageBox::Cancel); msgBox.setDefaultButton(QMessageBox::Cancel); int ret = msgBox.exec(); if (ret == QMessageBox::Ok) doCopy = true; else doCopy = false; } else doCopy = true; if (doCopy) { targetFile.remove(); if (sourceFile.copy(targetName)) { filesDone++; } else { errorMessage = tr ("Can't copy file") + " " + sourceName + " " + tr("to") + " " + targetName; } } } } if (errorMessage != "") { if (i < l - 1) { QMessageBox msgBox; msgBox.setText(tr("Error copying file")); msgBox.setInformativeText (errorMessage + ". " + tr("Do you want to coninue with the next item?")); msgBox.setStandardButtons(QMessageBox::Ok | QMessageBox::Cancel); msgBox.setDefaultButton(QMessageBox::Cancel); int ret = msgBox.exec(); if (ret != QMessageBox::Ok) stop = true; } else error (errorMessage); } progress.setValue (i); } if (progress.wasCanceled()) message ("canceled"); progress.setValue (l); ret = true; if (stop) ret = false; if (progress.wasCanceled()) ret = false; if (errorMessage != "") ret = false; emit dirContentsChanged(); QString sm = tr("Copied"); char ss[20]; sprintf (ss, "%d", filesDone); sm += ss; sm += " " + (filesDone == 1 ? tr("file") : tr("files")); emit statusUpdate (sm); return ret; }
KOnlineBankingSetupWizard::KOnlineBankingSetupWizard(QWidget *parent): QWizard(parent), d(new Private), m_fDone(false), m_fInit(false), m_appId(0) { setupUi(this); m_applicationEdit->hide(); m_headerVersionEdit->hide(); #ifndef LIBOFX_HAVE_CLIENTUID m_editClientUid->setEnabled(false); m_clientUidLabel->setEnabled(false); #endif m_appId = new OfxAppVersion(m_applicationCombo, m_applicationEdit, ""); m_headerVersion = new OfxHeaderVersion(m_headerVersionCombo, ""); // fill the list view with banks QProgressDialog* dlg = new QProgressDialog(this); dlg->setWindowTitle(i18n("Loading banklist")); dlg->setLabelText(i18n("Getting list of banks from http://moneycentral.msn.com/\nThis may take some time depending on the available bandwidth.")); dlg->setModal(true); dlg->setCancelButton(0); // force to show immediately as the call to OfxPartner::BankNames() // does not call the processEvents() loop dlg->setMinimumDuration(0); QCoreApplication::processEvents(); //set password field according to KDE preferences m_editPassword->setPasswordMode(true); KListWidgetSearchLine* searchLine = new KListWidgetSearchLine(autoTab, m_listFi); vboxLayout1->insertWidget(0, searchLine); QTimer::singleShot(20, searchLine, SLOT(setFocus())); OfxPartner::setDirectory(QStandardPaths::writableLocation(QStandardPaths::DataLocation) + QLatin1Char('/') + ""); m_listFi->addItems(OfxPartner::BankNames()); m_fInit = true; delete dlg; checkNextButton(); connect(this, SIGNAL(currentIdChanged(int)), this, SLOT(checkNextButton())); connect(this, SIGNAL(currentIdChanged(int)), this, SLOT(newPage(int))); connect(m_listFi, SIGNAL(itemSelectionChanged()), this, SLOT(checkNextButton())); connect(m_listAccount, SIGNAL(itemSelectionChanged()), this, SLOT(checkNextButton())); connect(m_selectionTab, SIGNAL(currentChanged(int)), this, SLOT(checkNextButton())); connect(m_fid, SIGNAL(userTextChanged(QString)), this, SLOT(checkNextButton())); connect(m_bankName, SIGNAL(userTextChanged(QString)), this, SLOT(checkNextButton())); connect(m_url, SIGNAL(textChanged(QString)), this, SLOT(checkNextButton())); connect(m_editUsername, SIGNAL(userTextChanged(QString)), this, SLOT(checkNextButton())); connect(m_editPassword, SIGNAL(userTextChanged(QString)), this, SLOT(checkNextButton())); connect(m_applicationEdit, SIGNAL(userTextChanged(QString)), this, SLOT(checkNextButton())); connect(m_applicationCombo, SIGNAL(currentIndexChanged(int)), this, SLOT(applicationSelectionChanged())); // setup text on buttons setButtonText(QWizard::NextButton, i18nc("Go to next page of the wizard", "&Next")); setButtonText(QWizard::BackButton, KStandardGuiItem::back().text()); // setup icons button(QWizard::FinishButton)->setIcon(KStandardGuiItem::ok().icon()); button(QWizard::CancelButton)->setIcon(KStandardGuiItem::cancel().icon()); button(QWizard::NextButton)->setIcon(KStandardGuiItem::forward(KStandardGuiItem::UseRTL).icon()); button(QWizard::BackButton)->setIcon(KStandardGuiItem::back(KStandardGuiItem::UseRTL).icon()); }
void ServiceCharges::slotCalculate() { QDate start = _start->getDate(); QDate end = _end->getDate(); int days = end - start + 1; // Validate data if (start.isNull()) { QString message = tr("A start date must be entered"); QMessageBox::critical(this, tr("Error"), message); _start->setFocus(); return; } if (end.isNull()) { QString message = tr("An end date must be entered"); QMessageBox::critical(this, tr("Error"), message); _end->setFocus(); return; } if (start > end) { QString message = tr("Invalid date range"); QMessageBox::critical(this, tr("Error"), message); _start->setFocus(); return; } QApplication::setOverrideCursor(waitCursor); qApp->processEvents(); // Select all customers vector<Customer> customers; CustomerSelect conditions; conditions.activeOnly = true; _quasar->db()->select(customers, conditions); // Get invoice terms _quasar->db()->invoiceTerms(_invoice_ids, _invoice_term_ids); // Setup progress dialog unsigned int custs = customers.size(); QString message = tr("Calculating service charges..."); QProgressDialog* progress = new QProgressDialog(message, tr("Cancel"), custs, this, "foo", true); progress->setMinimumDuration(0); progress->setCaption(tr("Progress")); // Process each customer fixed totalCharges; _charges->clear(); for (unsigned int i = 0; i < custs; ++i) { progress->setProgress(i); qApp->processEvents(); if (progress->wasCancelled()) { _charges->clear(); QApplication::restoreOverrideCursor(); QString message = tr("Service charge calculation cancelled"); QMessageBox::information(this, tr("Cancelled"), message); return; } const Customer& customer = customers[i]; if (customer.serviceCharge() == 0.0) continue; double dailyRate = customer.serviceCharge().toDouble() * 1000.0/365.0; // Get all transactions for customer GltxSelect conditions; conditions.activeOnly = true; conditions.card_id = customer.id(); _quasar->db()->select(_gltxs, conditions); if (_gltxs.size() == 0) continue; // Remove all that don't effect card balance for (int k = _gltxs.size() - 1; k >= 0; --k) { const Gltx& gltx = _gltxs[k]; if (gltx.cardTotal() != 0.0) continue; _gltxs.erase(_gltxs.begin() + k); } // Sort by date std::sort(_gltxs.begin(), _gltxs.end()); // Allocate unallocated payments for (unsigned int j = 0; j < _gltxs.size(); ++j) { const Gltx& payment = _gltxs[j]; if (payment.cardTotal() >= 0.0) continue; if (payment.cardTotal() == payment.paymentTotal()) continue; fixed alloc = -(payment.cardTotal() - payment.paymentTotal()); for (unsigned int k = 0; k < _gltxs.size(); ++k) { Gltx& gltx = _gltxs[k]; if (gltx.cardTotal() <= 0.0) continue; if (gltx.cardTotal() == gltx.paymentTotal()) continue; fixed pay = gltx.cardTotal() - gltx.paymentTotal(); if (pay > alloc) pay = alloc; gltx.payments().push_back(PaymentLine(payment.id(), pay, 0.0)); alloc -= pay; if (alloc == 0.0) break; } // If not all allocated then nothing left to allocate against if (alloc != 0.0) break; } // Calculate service charge total double totalCharge = 0.0; for (unsigned int j = 0; j < _gltxs.size(); ++j) { const Gltx& gltx = _gltxs[j]; if (gltx.cardTotal() < 0.0) continue; for (int day = 0; day < days; ++day) { fixed balance = balanceOn(gltx, start + day); double charge = balance.toDouble() * dailyRate; totalCharge += charge; } } // Adjust and round fixed serviceCharge = totalCharge / 100000.0; serviceCharge.moneyRound(); if (serviceCharge <= 0.0) continue; ListViewItem* item = new ListViewItem(_charges, customer.id()); item->setValue(0, customer.name()); item->setValue(1, serviceCharge); totalCharges += serviceCharge; } ListViewItem* item = new ListViewItem(_charges); item->isLast = true; item->setValue(0, "Total"); item->setValue(1, totalCharges); progress->setProgress(custs); delete progress; QApplication::restoreOverrideCursor(); message = tr("Service charge calculation is complete"); QMessageBox::information(this, tr("Complete"), message); }
bool BpDocument::composeGraphs( bool lineGraphs, bool showDialogs ) { // Bar graph settings int tics = 2; double max = 100.; double min = 0.; // Line graph settings if ( lineGraphs ) { tics = 11; max = tableRow( tableRows()-1 ); min = tableRow(0); } GraphAxleParms *xParms = new GraphAxleParms( min, max, tics ); checkmem( __FILE__, __LINE__, xParms, "GraphAxleParms xParms", 1 ); if ( lineGraphs && min > 0. && property()->boolean( "graphXOriginAtZero" ) ) { xParms->useOrigin(); } // Determine the x-, y-, and z-variables. EqVar *xVar = m_eqTree->m_rangeVar[0]; EqVar *zVar = m_eqTree->m_rangeVar[1]; EqVar *yVar = 0; //-------------------------------------------------------------------------- // 2: Determine nice axis parameters for the x- and all the y-variables. //-------------------------------------------------------------------------- // Initialize the Y axle for each graph to a nice range QPtrList<GraphAxleParms> *yParmsList = new QPtrList<GraphAxleParms>(); yParmsList->setAutoDelete( true ); GraphAxleParms *yParms = 0; int yid; for ( yid = 0; yid < tableVars(); yid++ ) { yVar = tableVar( yid ); yParms = 0; // The yVar must be continuous. if ( yVar->isContinuous() ) { // Get Y range if ( lineGraphs ) { graphYMinMax( yid, min, max ); } else { barYMinMax( yid, min, max ); } // Determine and store nice axis parameters tics = 11; yParms = new GraphAxleParms( min, max, tics ); checkmem( __FILE__, __LINE__, yParms, "GraphAxleParms yParms", 1 ); yParmsList->append( yParms ); // If bar graph, or line graphs must start at origin if ( min > 0. ) { if ( ! lineGraphs || property()->boolean( "graphYOriginAtZero" ) ) { yParms->useOrigin(); } } // If min and max are the same, make them different if ( min == max ) { yParms->setAxle( min-1., max+1., 3 ); } } } //-------------------------------------------------------------------------- // 1: Allow the user to change the axle parameters. //-------------------------------------------------------------------------- if ( showDialogs && property()->boolean( "graphYUserRange" ) ) { GraphLimitsDialog *dialog = new GraphLimitsDialog( this, yParmsList, "graphLimitsDialog" ); checkmem( __FILE__, __LINE__, dialog, "GraphLimitsDialog dialog", 1 ); if ( dialog->exec() == QDialog::Accepted ) { dialog->store(); } delete dialog; dialog = 0; } //-------------------------------------------------------------------------- // 3: Draw each graph. //-------------------------------------------------------------------------- // Set up the progress dialog. int step = 0; int steps = tableVars(); QString text(""), button(""); if ( lineGraphs ) { translate( text, "BpDocument:Graphs:DrawingLineGraphs" ); } else { translate( text, "BpDocument:Graphs:DrawingBarGraphs" ); } translate( button, "BpDocument:Graphs:Abort" ); QProgressDialog *progress = new QProgressDialog( QString( text ).arg( steps ), button, steps ); Q_CHECK_PTR( progress ); progress->setMinimumDuration( 0 ); progress->setProgress( 0 ); // Loop for each output variable: one graph is composed per output variable. bool result = true; for ( yid = 0, yParms = yParmsList->first(); yid < tableVars(); yid++ ) { yVar = tableVar( yid ); // The yVar must be continuous. if ( yVar->isContinuous() ) { // Recompute nice Y axis //min = ( yParms->m_axleMin < yParms->m_dataMin ) // ? yParms->m_axleMin // : yParms->m_dataMin; min = yParms->m_axleMin; //max = ( yParms->m_axleMax > yParms->m_dataMax ) // ? yParms->m_axleMax // : yParms->m_dataMax; max = yParms->m_axleMax; // If min and max are the same, make them different tics = 11; if ( min == max ) { yParms->setAxle( min-1., max+1., 3 ); } // Compose this graph. if ( lineGraphs ) { composeLineGraph( yid, xVar, yVar, zVar, xParms, yParms ); } else { composeBarGraph( yid, xVar, yVar, xParms, yParms ); } // Update progress dialog. progress->setProgress( ++step ); qApp->processEvents(); if ( progress->wasCancelled() ) { result = false; break; } yParms = yParmsList->next(); } } // Cleanup and return. delete progress; progress = 0; delete xParms; xParms = 0; delete yParmsList; yParmsList = 0; return( result ); }
void inputRZImpl::print() { QString fname = EGSdir + EGSfileName; QPrinter* printer = new QPrinter; printer->setPageSize( QPrinter::Letter ); const int Margin = 20; const int MarginY = 30; int pageNo = 1; QPrintDialog pdialog(printer,this); if ( pdialog.exec()) { cout << "let's print !!!" << endl; QPainter paint( printer ); //if( !paint.begin( printer ) ) // paint on printer // return; static const char *fonts[] = { "Helvetica", "Courier", "Times", 0 }; static int sizes[] = { 10, 12, 18, 24, 36, 0 }; int yPos = 0; QFont fontNormal( fonts[1], sizes[0] ); QFont fontBold( fonts[0], sizes[0] ); fontBold.setWeight( QFont::Black); paint.setFont( fontBold ); QFontMetrics fmBold = paint.fontMetrics(); paint.setFont( fontNormal ); QFontMetrics fm = paint.fontMetrics(); //qt3to4 -- BW //Q3PaintDeviceMetrics metrics( printer ); // need width/height QFile fi( fname ); //qt3to4 -- BW //Q3TextStream ts( &fi ); QTextStream ts( &fi ); QString t; int StepsPerPage = 500; int LinesPerPage = (printer->height() - 2* MarginY) / fm.lineSpacing(); if ( fi.open( QIODevice::ReadOnly ) ) { int NumOfPages = 1 + TotalTextLines( fname ) / LinesPerPage; int totalSteps = StepsPerPage * NumOfPages; QString msg( "Printing (page " ); msg += QString::number( pageNo ); msg += ")..."; //qt3to4 -- BW //Q3ProgressDialog* dialog = new Q3ProgressDialog(msg, "Cancel", // totalSteps, this, "progress", true); QProgressDialog* dialog = new QProgressDialog(msg, "Cancel",0,totalSteps); //dialog->setTotalSteps( totalSteps ); //dialog->setProgress( 0 ); dialog->setValue(0); dialog->setMinimumDuration( 0 ); int progress_count = 0; QString gui = "EGSnrc GUI for RZ Geometries: " + EGSfileName; QDate currDate = QDate::currentDate(); QString date = currDate.toString ( "dd.MM.yyyy" ); paint.setFont( fontBold ); paint.drawText( Margin, 0, printer->width() - 2*Margin, fmBold.lineSpacing(), Qt::AlignLeft | Qt::RichText, gui ); paint.drawText( Margin, 0, printer->width() - 2*Margin, fmBold.lineSpacing(), Qt::AlignRight, date ); paint.drawLine( Margin, MarginY - 10, printer->width() - Margin, MarginY - 10 ); paint.drawLine( Margin, printer->height() - MarginY + 10, printer->width() - Margin, printer->height() - MarginY + 10 ); paint.drawText( Margin, printer->height() - fmBold.lineSpacing(), printer->width(), fmBold.lineSpacing(), Qt::AlignHCenter, QString::number( pageNo ) ); paint.setFont( fontNormal ); do { progress_count++; qApp->processEvents(); if ( dialog->wasCanceled() ) dialog->close(); t = ts.readLine(); if ( MarginY + yPos + fm.lineSpacing() > printer->height() - MarginY ) { do{ //dialog->setProgress( ++progress_count ); dialog->setValue(++progress_count ); }while ( progress_count < StepsPerPage*pageNo ); msg = "Printing (page " + QString::number( ++pageNo ) + ")..."; dialog->setLabelText( msg ); printer->newPage(); // no more room on this page yPos = 0; // back to top of page paint.setFont( fontBold ); paint.drawText( Margin, 0, printer->width() - 2*Margin, fmBold.lineSpacing(), Qt::AlignLeft | Qt::RichText, gui ); paint.drawText( Margin, 0, printer->width() - 2*Margin, fmBold.lineSpacing(), Qt::AlignRight, date ); paint.drawLine( Margin, MarginY - 10, printer->width() - Margin, MarginY - 10 ); paint.drawLine( Margin, printer->height() - MarginY + 10, printer->width() - Margin, printer->height() - MarginY + 10 ); paint.drawText( Margin, printer->height() - fmBold.lineSpacing(), printer->width(), fmBold.lineSpacing(), Qt::AlignHCenter, QString::number( pageNo ) ); paint.setFont( fontNormal ); } paint.drawText( Margin, MarginY + yPos, printer->width(), fm.lineSpacing(), Qt::TextExpandTabs | Qt::TextDontClip, t ); yPos = yPos + fm.lineSpacing(); dialog->setValue( progress_count ); //qt3to4 -- BW //} while ( !ts.eof() ); } while ( !ts.atEnd() ); do{ dialog->setValue( ++progress_count ); }while ( progress_count < totalSteps ); dialog->setValue( totalSteps ); zap(dialog); } else { QMessageBox::critical( 0, tr("Error printing "), tr("Couldn't open file %1").arg(fname), tr("Quit") ); } fi.close(); } else { QMessageBox::information( this, "Printing status", "Printing aborted"); } delete printer; }
/*========================================================================= cutFromClipboard =========================================================================*/ bool KFileBrowser::cutFromClipboard (const FileClipboard *fc) { const QStringList &names = fc->getNames(); QMessageBox msgBox; msgBox.setText(tr("Confirm move")); if (names.count() == 1) msgBox.setInformativeText (tr("Do you want to move this item?")); else { char ss[20]; sprintf (ss, "%d", names.count()); msgBox.setInformativeText ((QString)tr("Do you want to move these") + " " + ss + " " + tr ("items") + "?"); } msgBox.setStandardButtons(QMessageBox::Ok | QMessageBox::Cancel); msgBox.setDefaultButton(QMessageBox::Cancel); int r = msgBox.exec(); if (r != QMessageBox::Ok) return false; bool ret = FALSE; const QString &root = fc->getRoot(); int l = names.count(); int itemsDone = 0; QProgressDialog progress (tr("Moving files..."), tr("Stop"), 0, l, this); progress.setWindowModality (Qt::WindowModal); progress.setMinimumDuration (0); progress.show(); bool stop = false; QString errorMessage = ""; for (int i = 0; i < l && !progress.wasCanceled() &&!stop; i++) { QString sourceName = root + "/" + names[i]; QString targetName; if (fc->getPasteByNameOnly()) { QFileInfo info (path + "/" + names[i]); QString shortName = info.fileName(); targetName = path + "/" + shortName; } else targetName = path + "/" + names[i]; errorMessage = ""; if (sourceName == targetName) { errorMessage = tr ("Source and destination files are the same"); } else { QFileInfo info (sourceName); if (info.isDir()) { QDir dir; if (dir.rename (sourceName, targetName)) itemsDone++; else errorMessage = tr("Can't move directory"); } else { QFile file; if (file.rename (sourceName, targetName)) itemsDone++; else errorMessage = tr("Can't move file"); } } if (errorMessage != "") { if (i < l - 1) { QMessageBox msgBox; msgBox.setText(tr("Error copying file")); msgBox.setInformativeText (errorMessage + ". " + tr("Do you want to coninue with the next item?")); msgBox.setStandardButtons(QMessageBox::Ok | QMessageBox::Cancel); msgBox.setDefaultButton(QMessageBox::Cancel); int ret = msgBox.exec(); if (ret != QMessageBox::Ok) stop = true; } else error (errorMessage); } progress.setValue (i); } if (progress.wasCanceled()) message ("canceled"); progress.setValue (l); ret = true; if (stop) ret = false; if (progress.wasCanceled()) ret = false; if (errorMessage != "") ret = false; emit dirContentsChanged(); QString sm = tr("Moved"); char ss[20]; sprintf (ss, "%d", itemsDone); sm += ss; sm += " " + (itemsDone == 1 ? tr("items") : tr("items")); emit statusUpdate (sm); return ret; }
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 ()); }
// Refresh not up to date metrics and metrics after date void MetricAggregator::refreshMetrics(QDateTime forceAfterThisDate) { // only if we have established a connection to the database if (dbaccess == NULL || context->athlete->isclean==true) return; // first check db structure is still up to date // this is because metadata.xml may add new fields dbaccess->checkDBVersion(); // Get a list of the ride files QRegExp rx = RideFileFactory::instance().rideFileRegExp(); QStringList filenames = RideFileFactory::instance().listRideFiles(context->athlete->home); QStringListIterator i(filenames); // get a Hash map of statistic records and timestamps QSqlQuery query(dbaccess->connection()); QHash <QString, status> dbStatus; bool rc = query.exec("SELECT filename, timestamp, fingerprint FROM metrics ORDER BY ride_date;"); while (rc && query.next()) { status add; QString filename = query.value(0).toString(); add.timestamp = query.value(1).toInt(); add.fingerprint = query.value(2).toInt(); dbStatus.insert(filename, add); } // begin LUW -- byproduct of turning off sync (nosync) dbaccess->connection().transaction(); // Delete statistics for non-existant ride files QHash<QString, status>::iterator d; for (d = dbStatus.begin(); d != dbStatus.end(); ++d) { if (QFile(context->athlete->home.absolutePath() + "/" + d.key()).exists() == false) { dbaccess->deleteRide(d.key()); #ifdef GC_HAVE_LUCENE context->athlete->lucene->deleteRide(d.key()); #endif } } unsigned long zoneFingerPrint = static_cast<unsigned long>(context->athlete->zones()->getFingerprint()) + static_cast<unsigned long>(context->athlete->hrZones()->getFingerprint()); // checksum of *all* zone data (HR and Power) // update statistics for ride files which are out of date // showing a progress bar as we go QTime elapsed; elapsed.start(); QString title = tr("Updating Statistics\nStarted"); QProgressDialog *bar = NULL; int processed=0; QApplication::processEvents(); // get that dialog up! // log of progress QFile log(context->athlete->home.absolutePath() + "/" + "metric.log"); log.open(QIODevice::WriteOnly); log.resize(0); QTextStream out(&log); out << "METRIC REFRESH STARTS: " << QDateTime::currentDateTime().toString() + "\r\n"; while (i.hasNext()) { QString name = i.next(); QFile file(context->athlete->home.absolutePath() + "/" + name); // if it s missing or out of date then update it! status current = dbStatus.value(name); unsigned long dbTimeStamp = current.timestamp; unsigned long fingerprint = current.fingerprint; RideFile *ride = NULL; processed++; // create the dialog if we need to show progress for long running uodate long elapsedtime = elapsed.elapsed(); if ((first || elapsedtime > 6000) && bar == NULL) { bar = new QProgressDialog(title, tr("Abort"), 0, filenames.count()); // not owned by mainwindow bar->setWindowFlags(bar->windowFlags() | Qt::FramelessWindowHint); bar->setWindowModality(Qt::WindowModal); bar->setMinimumDuration(0); bar->show(); // lets hide until elapsed time is > 6 seconds } // update the dialog always after 6 seconds if (first || elapsedtime > 6000) { // update progress bar QString elapsedString = QString("%1:%2:%3").arg(elapsedtime/3600000,2) .arg((elapsedtime%3600000)/60000,2,10,QLatin1Char('0')) .arg((elapsedtime%60000)/1000,2,10,QLatin1Char('0')); QString title = tr("%1\n\nUpdate Statistics\nElapsed: %2\n\n%3").arg(context->athlete->cyclist).arg(elapsedString).arg(name); bar->setLabelText(title); bar->setValue(processed); } QApplication::processEvents(); if (dbTimeStamp < QFileInfo(file).lastModified().toTime_t() || zoneFingerPrint != fingerprint || (!forceAfterThisDate.isNull() && name >= forceAfterThisDate.toString("yyyy_MM_dd_hh_mm_ss"))) { QStringList errors; // log out << "Opening ride: " << name << "\r\n"; // read file and process it if we didn't already... if (ride == NULL) ride = RideFileFactory::instance().openRideFile(context, file, errors); out << "File open completed: " << name << "\r\n"; if (ride != NULL) { out << "Getting weight: " << name << "\r\n"; ride->getWeight(); out << "Updating statistics: " << name << "\r\n"; importRide(context->athlete->home, ride, name, zoneFingerPrint, (dbTimeStamp > 0)); } } // update cache (will check timestamps itself) // if ride wasn't opened it will do it itself // we only want to check so passing check=true // because we don't actually want the results now RideFileCache updater(context, context->athlete->home.absolutePath() + "/" + name, ride, true); // free memory - if needed if (ride) delete ride; if (bar && bar->wasCanceled()) { out << "METRIC REFRESH CANCELLED\r\n"; break; } } // now zap the progress bar if (bar) delete bar; // end LUW -- now syncs DB out << "COMMIT: " << QDateTime::currentDateTime().toString() + "\r\n"; dbaccess->connection().commit(); #ifdef GC_HAVE_LUCENE #ifndef WIN32 // windows crashes here.... out << "OPTIMISE: " << QDateTime::currentDateTime().toString() + "\r\n"; context->athlete->lucene->optimise(); #endif #endif context->athlete->isclean = true; // stop logging out << "SIGNAL DATA CHANGED: " << QDateTime::currentDateTime().toString() + "\r\n"; dataChanged(); // notify models/views out << "METRIC REFRESH ENDS: " << QDateTime::currentDateTime().toString() + "\r\n"; log.close(); first = false; }
void ItemInquiry::slotRefresh(QDate from, QDate to, Id store_id) { if (loading) return; loading = true; needsRefresh = false; delete _grid; _grid = NULL; // Clear data list->clear(); for (int label = 0; label < 10; ++label) labels[label]->setText(" "); // Get item to show and return if none Id item_id = search->getId(); if (item_id == INVALID_ID) { loading = false; return; } setEnabled(false); QApplication::setOverrideCursor(waitCursor); qApp->processEvents(); // Get item information Item item; quasar->db()->lookup(item_id, item); fixed beginOnHand = 0.0; fixed beginCost = 0.0; fixed beginOnOrder = 0.0; fixed totalDebits = 0.0; fixed totalCredits = 0.0; labels[0]->setText(tr("Beginning Balance")); labels[1]->setText(tr("Total Increase")); labels[2]->setText(tr("Total Decrease")); labels[3]->setText(tr("Net Change")); labels[4]->setText(tr("Ending Balance")); // Get beginning balance if (!from.isNull()) quasar->db()->itemGeneral(item.id(), "", store_id, from - 1, beginOnHand, beginCost, beginOnOrder); // Select transactions vector<Gltx> gltxs; vector<fixed> quantities; vector<fixed> ext_costs; vector<fixed> ext_prices; vector<bool> void_flags; quasar->db()->selectItem(item.id(), store_id, from, to, gltxs, quantities, ext_costs, ext_prices, void_flags); // Setup grid _grid = new Grid(8); Grid* header = new Grid(1, _grid); TextFrame* text; text = new TextFrame(tr("Item Inquiry"), header); text->setFont(Font("Times", 24)); header->set(USE_NEXT, 0, text); text = new TextFrame(item.number() + " " + item.description(), header); text->setFont(Font("Times", 18)); header->set(USE_NEXT, 0, text); text = new TextFrame(DateValcon().format(from) + tr(" to ") + DateValcon().format(to), header); text->setFont(Font("Times", 18)); header->set(USE_NEXT, 0, text); header->setColumnWeight(0, 1); _grid->set(0, 0, 1, _grid->columns(), header, Grid::AllSides); _grid->set(USE_NEXT, 0, ""); for (int column = 0; column < 8; ++column) { _grid->setColumnSticky(column, column < 4 ? Grid::Left : Grid::Right); _grid->setColumnPad(column, 5); } _grid->set(2, 0, tr("Type")); _grid->set(3, 0, new LineFrame(_grid), Grid::LeftRight); _grid->set(2, 1, tr("Id #")); _grid->set(3, 1, new LineFrame(_grid), Grid::LeftRight); _grid->set(2, 2, tr("Store")); _grid->set(3, 2, new LineFrame(_grid), Grid::LeftRight); _grid->set(2, 3, tr("Date")); _grid->set(3, 3, new LineFrame(_grid), Grid::LeftRight); _grid->set(2, 4, tr("Memo")); _grid->set(3, 4, new LineFrame(_grid), Grid::LeftRight); _grid->set(2, 5, tr("Debit")); _grid->set(3, 5, new LineFrame(_grid), Grid::LeftRight); _grid->set(2, 6, tr("Credit")); _grid->set(3, 6, new LineFrame(_grid), Grid::LeftRight); _grid->set(2, 7, tr("Voided?")); _grid->set(3, 7, new LineFrame(_grid), Grid::LeftRight); _grid->setHeaderRows(_grid->rows()); // Setup progress dialog QProgressDialog* progress = new QProgressDialog(tr("Loading data..."), tr("Cancel"), gltxs.size(), this, "Progress", true); progress->setMinimumDuration(1000); progress->setCaption(tr("Progress")); // Process each transaction for (unsigned int i = 0; i < gltxs.size(); ++i) { const Gltx& gltx = gltxs[i]; fixed ext_cost = ext_costs[i]; // TODO: pick to show cost, qty, or price if (i % 50 == 0) { progress->setProgress(i); qApp->processEvents(); if (progress->wasCancelled()) { break; } } // Don't show voided lines or quotes if (void_flags[i] || gltx.dataType() == DataObject::QUOTE) continue; Store store; quasar->db()->lookup(gltx.storeId(), store); ListViewItem* item = new ListViewItem(list, gltx.id()); item->setValue(0, gltx.dataTypeName()); item->setValue(1, gltx.number()); item->setValue(2, store.number()); item->setValue(3, gltx.postDate()); item->setValue(4, gltx.memo()); item->setValue(7, !gltx.isActive()); _grid->set(USE_NEXT, 0, gltx.dataTypeName()); _grid->set(USE_CURR, 1, gltx.number()); _grid->set(USE_CURR, 2, store.number()); _grid->set(USE_CURR, 3, DateValcon().format(gltx.postDate())); _grid->set(USE_CURR, 4, gltx.memo()); _grid->set(USE_CURR, 7, gltx.isActive() ? " " : "x"); // Correct sign based on type switch (gltx.dataType()) { case DataObject::INVOICE: case DataObject::RETURN: ext_cost = -ext_cost; break; default: break; } if (ext_cost >= 0.0) { item->setValue(5, ext_cost); _grid->set(USE_CURR, 5, MoneyValcon().format(ext_cost)); if (gltx.isActive()) totalDebits += ext_cost; } else { item->setValue(6, -ext_cost); _grid->set(USE_CURR, 6, MoneyValcon().format(-ext_cost)); if (gltx.isActive()) totalCredits += -ext_cost; } } progress->setProgress(gltxs.size()); delete progress; // Set bottom totals fixed netChange = totalDebits - totalCredits; fixed endBalance = beginCost + netChange; MoneyValcon moneyValcon; labels[5]->setText(moneyValcon.format(beginCost)); labels[6]->setText(moneyValcon.format(totalDebits)); labels[7]->setText(moneyValcon.format(totalCredits)); labels[8]->setText(moneyValcon.format(netChange)); labels[9]->setText(moneyValcon.format(endBalance)); _grid->set(USE_NEXT, 0, ""); _grid->set(USE_NEXT, 0, 1, 5, tr("Beginning Balance"), Grid::Right); _grid->set(USE_CURR, 5, 1, 2, MoneyValcon().format(beginCost)); _grid->set(USE_NEXT, 0, 1, 5, tr("Total Debits"), Grid::Right); _grid->set(USE_CURR, 5, 1, 2, MoneyValcon().format(totalDebits)); _grid->set(USE_NEXT, 0, 1, 5, tr("Total Credits"), Grid::Right); _grid->set(USE_CURR, 5, 1, 2, MoneyValcon().format(totalCredits)); _grid->set(USE_NEXT, 0, 1, 5, tr("Net Change"), Grid::Right); _grid->set(USE_CURR, 5, 1, 2, MoneyValcon().format(netChange)); _grid->set(USE_NEXT, 0, 1, 5, tr("Ending Balance"), Grid::Right); _grid->set(USE_CURR, 5, 1, 2, MoneyValcon().format(endBalance)); QApplication::restoreOverrideCursor(); setEnabled(true); loading = false; }
void Journal::slotRealRefresh() { if (_loading) return; _loading = true; setEnabled(false); QApplication::setOverrideCursor(waitCursor); qApp->processEvents(); // Disabled updates so that progress bar updating doesn't also do lists _general->setUpdatesEnabled(false); _disbursements->setUpdatesEnabled(false); _receipts->setUpdatesEnabled(false); _sales->setUpdatesEnabled(false); _purchases->setUpdatesEnabled(false); _inventory->setUpdatesEnabled(false); _all->setUpdatesEnabled(false); // Load accounts if needed if (_accounts.size() == 0) { _quasar->db()->select(_accounts, AccountSelect()); } // Clear out old values _general->clearList(); _disbursements->clearList(); _receipts->clearList(); _sales->clearList(); _purchases->clearList(); _inventory->clearList(); _all->clearList(); _lastStart = _from->getDate(); _lastEnd = _to->getDate(); int days = _lastEnd - _lastStart + 1; // Setup progress dialog QProgressDialog* progress = new QProgressDialog(tr("Loading transactions..."), tr("Cancel"), days, this, "Progress", true); progress->setMinimumDuration(0); progress->setCaption(tr("Progress")); for (int day = 0; day < days; ++day) { loadDate(_lastStart + day); progress->setProgress(day); qApp->processEvents(); if (progress->wasCancelled()) { // TODO: add cancelled line break; } } progress->setProgress(days); delete progress; // Enable updates on lists _general->setUpdatesEnabled(true); _disbursements->setUpdatesEnabled(true); _receipts->setUpdatesEnabled(true); _sales->setUpdatesEnabled(true); _purchases->setUpdatesEnabled(true); _inventory->setUpdatesEnabled(true); _all->setUpdatesEnabled(true); QApplication::restoreOverrideCursor(); setEnabled(true); _loading = false; _refreshPending = false; }
void Main_GUI::run() { statusBar()->clearMessage(); QString input_name = QDir::fromNativeSeparators(input_line->text()); QString output_name = QDir::fromNativeSeparators(output_line->text()); if (!check_filenames(input_name, output_name)) return; // we need C file descriptors for communication with TTF_autohint FILE* input; FILE* output; again: if (!open_files(input_name, &input, output_name, &output)) return; QProgressDialog dialog; dialog.setCancelButtonText(tr("Cancel")); dialog.setMinimumDuration(1000); dialog.setWindowModality(Qt::WindowModal); const unsigned char* error_string; TA_Info_Func info_func = info; GUI_Progress_Data gui_progress_data = {-1, true, &dialog}; Info_Data info_data; info_data.data = NULL; // must be deallocated after use info_data.data_wide = NULL; // must be deallocated after use info_data.data_len = 0; info_data.data_wide_len = 0; info_data.hinting_range_min = min_box->value(); info_data.hinting_range_max = max_box->value(); info_data.hinting_limit = no_limit_box->isChecked() ? 0 : limit_box->value(); info_data.gray_strong_stem_width = gray_box->isChecked(); info_data.gdi_cleartype_strong_stem_width = gdi_box->isChecked(); info_data.dw_cleartype_strong_stem_width = dw_box->isChecked(); info_data.increase_x_height = no_increase_box->isChecked() ? 0 : increase_box->value(); info_data.x_height_snapping_exceptions = x_height_snapping_exceptions; info_data.windows_compatibility = wincomp_box->isChecked(); info_data.pre_hinting = pre_box->isChecked(); info_data.hint_with_components = hint_box->isChecked(); info_data.latin_fallback = fallback_box->currentIndex(); info_data.symbol = symbol_box->isChecked(); if (info_box->isChecked()) { int ret = build_version_string(&info_data); if (ret == 1) QMessageBox::information( this, "TTFautohint", tr("Can't allocate memory for <b>TTFautohint</b> options string" " in <i>name</i> table."), QMessageBox::Ok, QMessageBox::Ok); else if (ret == 2) QMessageBox::information( this, "TTFautohint", tr("<b>TTFautohint</b> options string" " in <i>name</i> table too long."), QMessageBox::Ok, QMessageBox::Ok); } else info_func = NULL; QByteArray snapping_string = snapping_line->text().toLocal8Bit(); TA_Error error = TTF_autohint("in-file, out-file," "hinting-range-min, hinting-range-max," "hinting-limit," "gray-strong-stem-width," "gdi-cleartype-strong-stem-width," "dw-cleartype-strong-stem-width," "error-string," "progress-callback, progress-callback-data," "info-callback, info-callback-data," "ignore-restrictions," "windows-compatibility," "pre-hinting," "hint-with-components," "increase-x-height," "x-height-snapping-exceptions," "fallback-script, symbol", input, output, info_data.hinting_range_min, info_data.hinting_range_max, info_data.hinting_limit, info_data.gray_strong_stem_width, info_data.gdi_cleartype_strong_stem_width, info_data.dw_cleartype_strong_stem_width, &error_string, gui_progress, &gui_progress_data, info_func, &info_data, ignore_restrictions, info_data.windows_compatibility, info_data.pre_hinting, info_data.hint_with_components, info_data.increase_x_height, snapping_string.constData(), info_data.latin_fallback, info_data.symbol); if (info_box->isChecked()) { free(info_data.data); free(info_data.data_wide); } fclose(input); fclose(output); if (error) { if (handle_error(error, error_string, output_name)) goto again; } else statusBar()->showMessage(tr("Auto-hinting finished.")); }
void PromoBatchMaster::slotPrint() { if (!saveItem(true)) return; dataToWidget(); // Setup grid for printing Grid* grid = new Grid(6); Grid* header = new Grid(1, grid); TextFrame* text; text = new TextFrame(tr("Promotion Batch"), header); text->setJustify(ALIGN_CENTER); text->setFont(Font("Times", 24, 75)); header->set(USE_NEXT, 0, text); if (_curr.executedOn().isNull()) { text = new TextFrame(tr("Preliminary"), header); } else { QString dateText = DateValcon().format(_curr.executedOn()); text = new TextFrame(tr("Executed On: %1").arg(dateText), header); } text->setJustify(ALIGN_CENTER); text->setFont(Font("Times", 18)); header->set(USE_NEXT, 0, text); header->setColumnWeight(0, 1); grid->set(0, 0, 1, grid->columns(), header, Grid::AllSides); grid->set(USE_NEXT, 0, ""); for (int column = 0; column < 6; ++column) { grid->setColumnSticky(column, column < 3 ? Grid::Left : Grid::Right); grid->setColumnPad(column, 5); } grid->set(2, 0, tr("Item Number")); grid->set(3, 0, new LineFrame(grid), Grid::LeftRight); grid->set(2, 1, tr("Description")); grid->set(3, 1, new LineFrame(grid), Grid::LeftRight); grid->set(2, 2, tr("Size")); grid->set(3, 2, new LineFrame(grid), Grid::LeftRight); grid->set(2, 3, tr("Current Price")); grid->set(3, 3, new LineFrame(grid), Grid::LeftRight); grid->set(2, 4, tr("Promo Price")); grid->set(3, 4, new LineFrame(grid), Grid::LeftRight); grid->set(2, 5, tr("Ordered")); grid->set(3, 5, new LineFrame(grid), Grid::LeftRight); grid->setHeaderRows(grid->rows()); // Setup progress dialog QProgressDialog* progress = new QProgressDialog(tr("Printing promos..."), tr("Cancel"), _curr.items().size(), this, "Progress", true); progress->setMinimumDuration(1000); progress->setCaption(tr("Progress")); // Print promos for (unsigned int i = 0; i < _curr.items().size(); ++i) { progress->setProgress(i); qApp->processEvents(); if (progress->wasCancelled()) break; Id item_id = _curr.items()[i].item_id; if (item_id == INVALID_ID) continue; QString number = _curr.items()[i].number; QString size = _curr.items()[i].size; Price promoPrice = _curr.items()[i].price; fixed ordered = _curr.items()[i].ordered; Item item; findItem(item_id, item); Price currentPrice = item.price(_store->getId(), size); grid->set(USE_NEXT, 0, number); grid->set(USE_CURR, 1, item.description()); grid->set(USE_CURR, 2, size); grid->set(USE_CURR, 3, currentPrice.toString()); grid->set(USE_CURR, 4, promoPrice.toString()); grid->set(USE_CURR, 5, ordered.toString()); } bool cancelled = progress->wasCancelled(); progress->setProgress(_curr.items().size()); delete progress; if (!cancelled) grid->print(this); delete grid; }
int main( int argc, char **argv ) { int i; QString m1,n1,o1; struct args pargs; QApplication *a; InitWidget *b; ScreenWidget *c; TextWidget *textOut; QProgressDialog *qProg; QPixmap *qpxMeshIcon=NULL; struct model_error model1,model2; int rcode; struct outbuf *log; struct prog_reporter pr; /* Initialize application */ a = NULL; b = NULL; c = NULL; qProg = NULL; memset(&model1,0,sizeof(model1)); memset(&model2,0,sizeof(model2)); memset(&pr,0,sizeof(pr)); log = NULL; i = 0; while (i<argc) { if (strcmp(argv[i],"-t") == 0) /* text version requested */ break; if (strcmp(argv[i],"-h") == 0) /* just asked for command line help */ break; i++; } if (i == argc) { /* no text version requested, initialize QT */ a = new QApplication( argc, argv ); /* Load pixmap for icon */ qpxMeshIcon = new QPixmap((const char**)meshIcon); if (a != NULL) a->connect( a, SIGNAL(lastWindowClosed()), a, SLOT(quit()) ); } else { a = NULL; /* No QT app needed */ } /* Parse arguments */ parse_args(argc,argv,&pargs); /* Display starting dialog if insufficient arguments */ if (pargs.m1_fname != NULL || pargs.m2_fname != NULL) { if (pargs.m1_fname == NULL || pargs.m2_fname == NULL) { fprintf(stderr,"ERROR: missing file name(s) in command line\n"); exit(1); } if (!pargs.do_wlog) { log = outbuf_new(stdio_puts,stdout); } else { textOut = new TextWidget(); textOut->setIcon(*qpxMeshIcon); log = outbuf_new(TextWidget_puts,textOut); textOut->show(); } if (pargs.no_gui) { pr.prog = stdio_prog; pr.cb_out = stdout; } else { qProg = new QProgressDialog("Calculating distance",0,100); qProg->setIcon(*qpxMeshIcon); qProg->setMinimumDuration(1500); pr.prog = QT_prog; pr.cb_out = qProg; } mesh_run(&pargs, &model1, &model2, log, &pr); } else { b = new InitWidget(pargs, &model1, &model2); b->setIcon(*qpxMeshIcon); b->show(); } if (a != NULL) { if (pargs.m1_fname != NULL || pargs.m2_fname != NULL) { c = new ScreenWidget(&model1, &model2, &pargs); c->setIcon(*qpxMeshIcon); a->setMainWidget(c); c->show(); } rcode = a->exec(); } else { rcode = 0; } /* Free widgets */ outbuf_delete(log); delete qProg; delete qpxMeshIcon; delete b; delete c; delete a; // QApplication must be last QT thing to delete /* Free model data */ if (model1.mesh != NULL) __free_raw_model(model1.mesh); free(model1.verror); free(model1.info); free_face_error(model1.fe); if (model2.mesh != NULL) __free_raw_model(model2.mesh); free(model2.verror); free(model2.info); /* Return exit code */ return rcode; }
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); }
void Uploading::uploadingProcess(const QString &actionId) { { QProgressDialog progressDialog; progressDialog.setWindowModality(Qt::WindowModal); progressDialog.setWindowTitle(tr("Выгрузка базы данных")); progressDialog.setLabelText(tr("Процесс выгрузки базы данных")); progressDialog.setCancelButton(0); progressDialog.setMinimumDuration(0); progressDialog.setMaximum(6); progressDialog.setValue(0); QSqlDatabase db = QSqlDatabase::database(UPLOADING); createDBScheme(); progressDialog.setValue(1); QApplication::processEvents(QEventLoop::ExcludeUserInputEvents); QSqlQuery selectDataQuery(QSqlDatabase::database(mConnection)); QSqlQuery insertDataQuery(db); if(selectDataQuery.exec("SELECT id, title, performer FROM Actions WHERE id = " + actionId)) { insertDataQuery.prepare("INSERT INTO Actions VALUES(:id, :title, :performer);"); while(selectDataQuery.next()) { insertDataQuery.bindValue(":id", selectDataQuery.value(0)); insertDataQuery.bindValue(":title", selectDataQuery.value(1)); insertDataQuery.bindValue(":performer", selectDataQuery.value(2)); insertDataQuery.exec(); } } progressDialog.setValue(2); QList<int> placeSchemeIds; QList<int> clientIds; if(selectDataQuery.exec("SELECT id, id_action, id_placeScheme, id_client, identifier FROM Tickets WHERE id_action = " + actionId)) { insertDataQuery.prepare("INSERT INTO Tickets VALUES(NULL, :id_action, :id_placeScheme, :id_client, :identifier, :passedFlag);"); while(selectDataQuery.next()) { insertDataQuery.bindValue(":id_action", selectDataQuery.value(1)); insertDataQuery.bindValue(":id_placeScheme", selectDataQuery.value(2)); insertDataQuery.bindValue(":id_client", selectDataQuery.value(3)); insertDataQuery.bindValue(":identifier", selectDataQuery.value(4)); insertDataQuery.bindValue(":passedFlag", "false"); insertDataQuery.exec(); if(selectDataQuery.isNull(2) == false) placeSchemeIds.append(selectDataQuery.value(2).toInt()); if(selectDataQuery.isNull(3) == false) clientIds.append(selectDataQuery.value(4).toInt()); } } progressDialog.setValue(3); if(placeSchemeIds.isEmpty() == false) { if(selectDataQuery.exec("SELECT id, seatNumber, row FROM PlaceSchemes")) { insertDataQuery.prepare("INSERT INTO PlaceSchemes VALUES(:id, :seatNumber, :row)"); while(selectDataQuery.next()) { if(placeSchemeIds.contains( selectDataQuery.value(0).toInt()) ) { insertDataQuery.bindValue(":id", selectDataQuery.value(0)); insertDataQuery.bindValue(":seatNumber", selectDataQuery.value(1)); insertDataQuery.bindValue(":row", selectDataQuery.value(2)); insertDataQuery.exec(); } } } } progressDialog.setValue(4); if(clientIds.isEmpty() == false) { if(selectDataQuery.exec("SELECT id, name, login FROM Clients")) { insertDataQuery.prepare("INSERT INTO Clients VALUES(:id, :name, :login)"); while(selectDataQuery.next()) { if(clientIds.contains( selectDataQuery.value(0).toInt() )) { insertDataQuery.bindValue(":id", selectDataQuery.value(0)); insertDataQuery.bindValue(":name", selectDataQuery.value(1)); insertDataQuery.bindValue(":login", selectDataQuery.value(2)); insertDataQuery.exec(); } } } } progressDialog.setValue(5); if(selectDataQuery.exec("SELECT id, id_client, identifier FROM ReturnedTickets WHERE id_action = " + actionId)) { insertDataQuery.prepare("INSERT INTO ReturnedTickets VALUES(NULL, :id_client, :identifier);"); while(selectDataQuery.next()) { insertDataQuery.bindValue(":id_client", selectDataQuery.value(1)); insertDataQuery.bindValue(":identifier", selectDataQuery.value(2)); insertDataQuery.exec(); } } progressDialog.setValue(6); progressDialog.close(); db.close(); } QSqlDatabase::removeDatabase(UPLOADING); }