void MessageBar::show( const QString& message, const QString& id ) { QLabel* label = findChild<QLabel*>( id ); if (label && id.size()) { if (message.isEmpty()) { QProgressBar* p = label->findChild<QProgressBar*>(); if (p) p->setRange( 0, 1 ), p->setValue( 1 ); QTimer::singleShot( 3000, label, SLOT(deleteLater()) ); } else label->setText( message ); return; } label = new QLabel( message, ui.papyrus ); label->setBackgroundRole( QPalette::Base ); label->setMargin( 8 ); label->setIndent( 4 ); label->setTextFormat( Qt::RichText ); label->setOpenExternalLinks( true ); label->setTextInteractionFlags( Qt::TextSelectableByMouse | Qt::LinksAccessibleByMouse ); ImageButton* close = new ImageButton( ":/buckets/radio_clear_all_x.png" ); QHBoxLayout* h = new QHBoxLayout( label ); h->addStretch(); if (id.size()) { label->setObjectName( id ); QProgressBar* p; h->addWidget( p = new QProgressBar ); p->setRange( 0, 0 ); p->setFixedWidth( 90 ); } h->addWidget( close ); h->setMargin( 4 ); label->setFixedWidth( width() ); label->adjustSize(); label->show(); ui.papyrus->move( 0, -label->height() ); doLayout(); connect( close, SIGNAL(clicked()), label, SLOT(deleteLater()) ); connect( label, SIGNAL(destroyed()), SLOT(onLabelDestroyed()), Qt::QueuedConnection ); m_timeline->setFrameRange( height(), ui.papyrus->height() ); m_timeline->start(); }
void tst_QProgressBar::text() { QProgressBar bar; bar.setRange(10, 10); bar.setValue(10); QCOMPARE(bar.text(), QString("100%")); bar.setRange(0, 10); QCOMPARE(bar.text(), QString("100%")); bar.setValue(5); QCOMPARE(bar.text(), QString("50%")); bar.setRange(0, 5); bar.setValue(0); bar.setRange(5, 5); QCOMPARE(bar.text(), QString()); }
void K3b::ImageWritingDialog::calculateMd5Sum( const QString& file ) { d->haveMd5Sum = false; if( !d->md5SumItem ) { d->md5SumItem = new QTreeWidgetItem( d->infoView ); } d->md5SumItem->setText( 0, i18n("MD5 Sum:") ); d->md5SumItem->setForeground( 0, d->infoTextColor ); d->md5SumItem->setTextAlignment( 0, Qt::AlignRight ); if( file != d->lastCheckedFile ) { QProgressBar* progress = new QProgressBar( d->infoView ); progress->setMaximumHeight( fontMetrics().height() ); progress->setRange( 0, 100 ); progress->setValue( 0 ); d->infoView->setItemWidget( d->md5SumItem, 1, progress ); d->lastCheckedFile = file; d->md5Job->setFile( file ); d->md5Job->start(); } else slotMd5JobFinished( true ); }
void MangaW::LookingForDB(void) { QWidget * loadingWidget = new QWidget; QVBoxLayout * loadingLayout = new QVBoxLayout; // Layout Vertical Box QLabel * loadingTexte = new QLabel("Restauration des sauvegardes"); // Label = Texte QProgressBar * loadingProgressBar = new QProgressBar; // Barre de progression loadingProgressBar->setRange(0, 0); // ProgressBar en "chargement indéfini" loadingLayout->addWidget(loadingTexte); loadingLayout->addWidget(loadingProgressBar); loadingWidget->setLayout(loadingLayout); // On ajoute le layout au Widget loadingWidget->show(); // On affiche le widget // On vérifie l'existance de la sauvegarde if ( T.DB_Existe() && T.DB_Charger() ) { loadingWidget->close(); this->ClassicStart(); } else { loadingWidget->close(); this->FirstStart(); } // --- }
void tst_QProgressBar::minMaxSameValue() { QProgressBar bar; bar.setRange(10, 10); bar.setValue(10); bar.show(); }
int Patcher::execMaj() { if (maj_avalible <= 0) return 0; QProgressBar progressBar; progressBar.setMaximumHeight(16); progressBar.setMaximumWidth(200); //progressBar->setTextVisible(false); progressBar.setRange(0,maj_avalible); this->statusBar()->addPermanentWidget(&progressBar, 0); this->statusBar()->showMessage(QString("Loading")); int nb = 0; int i = 1; for(patcher::Maj& maj : majs) { this->statusBar()->showMessage(QString("download "+QString::number(i)+"/"+QString::number(maj_avalible))); if(not maj.isDone()) nb+= maj.apply(); progressBar.setValue(++i); } this->statusBar()->clearMessage(); this->statusBar()->removeWidget(&progressBar); return nb; }
int main(int argc, char ** argv) { using Q = QObject; QApplication app{argc, argv}; QWidget ui; QVBoxLayout layout{&ui}; QTextBrowser log; QProgressBar bar; QPushButton scan{"Scan localhost"}; layout.addWidget(&log); layout.addWidget(&bar); layout.addWidget(&scan); bar.setRange(1, 65535); ui.show(); Scanner scanner; Q::connect(&scan, &QPushButton::clicked, &scanner, [&]{ scan.setEnabled(false); scanner.start(); }); Q::connect(&scanner, &Scanner::hasResult, &log, [&](int port, bool isOpen){ bar.setValue(port); if (!isOpen) return; auto color = isOpen ? QStringLiteral("green") : QStringLiteral("red"); auto state = isOpen ? QStringLiteral("open") : QStringLiteral("closed"); log.append(QStringLiteral("<font color=\"%1\">Port %2 is %3.</font><br/>"). arg(color).arg(port).arg(state)); }); Q::connect(&scanner, &Scanner::done, &scan, [&]{ bar.reset(); scan.setEnabled(true); }); return app.exec(); }
void BackupDialog::backup() { QDir dir; // Compute a default file name & path (eg. "Baskets_2007-01-31.tar.gz"): KConfig *config = KGlobal::config().data(); KConfigGroup configGroup(config, "Backups"); QString folder = configGroup.readEntry("lastFolder", QDir::homePath()) + "/"; QString fileName = i18np("Backup filename (without extension), %1 is the date", "Baskets_%1", QDate::currentDate().toString(Qt::ISODate)); QString url = folder + fileName; // Ask a file name & path to the user: QString filter = "*.tar.gz|" + i18n("Tar Archives Compressed by Gzip") + "\n*|" + i18n("All Files"); QString destination = url; for (bool askAgain = true; askAgain;) { // Ask: destination = KFileDialog::getSaveFileName(destination, filter, 0, i18n("Backup Baskets")); // User canceled? if (destination.isEmpty()) return; // File already existing? Ask for overriding: if (dir.exists(destination)) { int result = KMessageBox::questionYesNoCancel( 0, "<qt>" + i18n("The file <b>%1</b> already exists. Do you really want to override it?", KUrl(destination).fileName()), i18n("Override File?"), KGuiItem(i18n("&Override"), "document-save") ); if (result == KMessageBox::Cancel) return; else if (result == KMessageBox::Yes) askAgain = false; } else askAgain = false; } KProgressDialog dialog(0, i18n("Backup Baskets"), i18n("Backing up baskets. Please wait...")); dialog.setModal(true); dialog.setAllowCancel(false); dialog.setAutoClose(true); dialog.show(); QProgressBar *progress = dialog.progressBar(); progress->setRange(0, 0/*Busy/Undefined*/); progress->setValue(0); progress->setTextVisible(false); BackupThread thread(destination, Global::savesFolder()); thread.start(); while (thread.isRunning()) { progress->setValue(progress->value() + 1); // Or else, the animation is not played! kapp->processEvents(); usleep(300); // Not too long because if the backup process is finished, we wait for nothing } Settings::setLastBackup(QDate::currentDate()); Settings::saveConfig(); populateLastBackup(); }
void BrowserView::onLoadStarted() { QProgressBar* bar = Gui::Sequencer::instance()->getProgressBar(); bar->setRange(0, 100); bar->show(); Gui::getMainWindow()->showMessage(tr("Loading %1...").arg(view->url().toString())); isLoading = true; }
void MessageDisplayWidget::appendProgress(const QString &filename, FileTransferState* state, bool isOur) { connect(verticalScrollBar(), &QScrollBar::rangeChanged, this, &MessageDisplayWidget::moveScrollBarToBottom, Qt::UniqueConnection); QProgressBar *row = new QProgressBar(this); row->setRange(0, 100); row->setFormat(QString("%1 - %p%").arg(QFileInfo(filename).baseName())); connect(state, &FileTransferState::progressChanged, row, &QProgressBar::setValue); mainlayout->addWidget(row); }
void tst_QProgressBar::formatedText() { QFETCH(int, minimum); QFETCH(int, maximum); QFETCH(int, value); QFETCH(QString, format); QFETCH(QString, text); QProgressBar bar; bar.setRange(minimum, maximum); bar.setValue(value); bar.setFormat(format); QCOMPARE(bar.text(), text); }
/** * @brief Updates the resolver pool display. */ void OpenNIC::updateResolverPool(QStringList resolverPool) { /* @brief <status>;<score>;<kind>;<hostAddress>; */ QTableWidget* table = ui->resolverPoolTable; double minScore,maxScore; scoreMinMax(resolverPool, minScore, maxScore); table->setRowCount(resolverPool.count()); for(int row=0; row < resolverPool.count(); row++ ) { QStringList elements = resolverPool.at(row).split(";"); QString ip = elements.at(3); QString kind = elements.at(2); QString score = elements.at(1); QString status = elements.at(0); QString statusIcon; if (status == "R") { status = tr("FAIL"); statusIcon = ":/images/status-red.png"; } else if (status == "G") { status = tr("OK"); statusIcon = ":/images/status-green.png"; } else if (status == "Y") { status = tr("WARN"); statusIcon = ":/images/status-yellow.png"; } table->setItem(row,3,new QTableWidgetItem(ip)); table->setItem(row,2,new QTableWidgetItem(kind)); #if 0 table->setItem(row,1,new QTableWidgetItem(score)); #else QProgressBar* bar = new QProgressBar(); bar->setRange((int)(minScore*1000.0),(int)(maxScore*1000.0)); bar->setValue((int)(score.toDouble()*1000.0)); table->setCellWidget(row,1,bar); #endif table->setItem(row,0,new QTableWidgetItem(QIcon(statusIcon),status)); } table->resizeColumnsToContents(); table->resizeRowsToContents(); table->setSortingEnabled(true); table->sortByColumn(1,Qt::DescendingOrder); }
ProgressUI::ProgressUI(QWidget *parent) : THWidgetBase(parent) { timerId = -1; gradient = 0; hideTitleBar(); setWindowFlags(Qt::FramelessWindowHint | Qt::WindowStaysOnTopHint | Qt::Tool); setWindowModality(Qt::ApplicationModal); QVBoxLayout *v = new QVBoxLayout(this); v->setContentsMargins(5, 5, 5, 5); v->setSpacing(0); lbl = new QLabel(this); lbl->setStyleSheet(QStringLiteral("font-family:΢ÈíÑźÚ;font:12px;color:white;")); QProgressBar *pbar = new QProgressBar(this); pbar->setRange(0, 100); pbar->setValue(0); pbar->setFixedSize(260, 12); QFile file; file.setFileName(":res/css/progressbar.css"); if (file.open(QIODevice::ReadOnly)) { QByteArray ba = file.readAll(); pbar->setStyleSheet(QTextCodec::codecForLocale()->toUnicode(ba)); } file.close(); v->addWidget(lbl, 1, Qt::AlignCenter); v->addWidget(pbar, 1, Qt::AlignCenter); setFixedSize(280, 50); connect(this, &ProgressUI::setValue, pbar, [=] (int value) { pbar->setValue(value); if (pbar->value() >= 100) { lbl->setText(QStringLiteral("Íê³É")); emit execFinished(); QTimer::singleShot(1000, this, [=] () { disconnect(this, 0, 0, 0); this->close(); this->deleteLater(); }); } }); timerId = startTimer(60/*, Qt::VeryCoarseTimer*/); }
void CalculateAmplitudes::setProgress(int row, int progress) { QProgressBar *progressBar = static_cast<QProgressBar*>(_ui.table->cellWidget(row, 3)); _ui.table->setItem(row, 3, NULL); if ( !progressBar ) { progressBar = new QProgressBar(_ui.table); progressBar->setRange(0, 100); progressBar->setAlignment(Qt::AlignHCenter); QPalette pal = progressBar->palette(); pal.setColor(QPalette::Highlight, Qt::darkGreen); progressBar->setPalette(pal); _ui.table->setCellWidget(row, 3, progressBar); } progressBar->setValue(progress); filterView(row, 1); }
UpdaterDialog::UpdaterDialog() : QProgressDialog("", tr("Cancel"), 0, 0) { setWindowTitle(tr("Updater - Lightscreen")); setWindowFlags(windowFlags() ^ Qt::WindowContextHelpButtonHint); setAutoClose(false); QProgressBar *bar = new QProgressBar(this); bar->setTextVisible(false); bar->setRange(0, 0); QLabel *label = new QLabel(tr("Checking for updates"), this); connect(label, SIGNAL(linkActivated(QString)), this, SLOT(link(QString))); setLabel(label); setBar(bar); }
UpdaterDialog::UpdaterDialog(QWidget *parent) : QProgressDialog("", tr("Cancel"), 0, 0, parent) { setWindowTitle(tr("Updater - Lightscreen")); setWindowFlags(windowFlags() ^ Qt::WindowContextHelpButtonHint); setAutoClose(false); QProgressBar *bar = new QProgressBar(this); bar->setTextVisible(false); bar->setRange(0, 0); QLabel *label = new QLabel(tr("Checking for updates..."), this); connect(label, &QLabel::linkActivated, this, &UpdaterDialog::link); setLabel(label); setBar(bar); }
void MainWindow::createProgressBar() { QxtProgressLabel* label = new QxtProgressLabel(statusBar()); QProgressBar* bar = new QProgressBar(statusBar()); bar->setMaximumWidth(label->sizeHint().width() * 2); bar->setRange(0, 120); QTimeLine* timeLine = new QTimeLine(120000, this); timeLine->setFrameRange(0, 120); connect(timeLine, SIGNAL(frameChanged(int)), bar, SLOT(setValue(int))); connect(timeLine, SIGNAL(finished()), label, SLOT(restart())); connect(bar, SIGNAL(valueChanged(int)), label, SLOT(setValue(int))); timeLine->start(); statusBar()->addPermanentWidget(new QLabel(tr("Dummy Progress:"), this)); statusBar()->addPermanentWidget(bar); statusBar()->addPermanentWidget(label); }
// Im Editor nach einer bestimmten Textfolge suchen void MyWindow::search( ) { bool ok; QString text = QInputDialog::getText( this, "Suchdialog", "Text zur Suche eingeben :", QLineEdit::Normal, "Suche eingeben", &ok ); // Einen einfachen Fortschrittsbalken zur Suche // in der Statusleiste simulieren QProgressBar* pbar = new QProgressBar; // min. und max. Werte festlegen pbar->setRange( 0, 500 ); statusBar()->addWidget(pbar); for (int i = 0; i < 500; i++) { pbar->setValue(i); for( int j=0; j < 12345678; ++j); //... copy one file } pbar->setValue(500); statusBar()->removeWidget(pbar); if (ok && !text.isEmpty()) editor->find(text); statusBar()->showMessage(tr("Suche beendet"), 3000); }
UpdateFC(LibASS *ass) : ass(ass) { start(); if (!wait(500)) { QDialog d(QMPlay2GUI.mainW); d.setWindowTitle(QCoreApplication::applicationName()); QLabel l(QObject::tr("Font cache is updating, please wait")); QProgressBar p; p.setRange(0, 0); QVBoxLayout la(&d); la.addWidget(&l); la.addWidget(&p); d.open(); d.setMinimumSize(d.size()); d.setMaximumSize(d.size()); do el.processEvents(QEventLoop::ExcludeUserInputEvents | QEventLoop::WaitForMoreEvents); while (isRunning()); } }
/*! Adds a progress bar to the bottom of the layout */ void ProgressWidget::addProgressBar(unsigned int timeStep, unsigned int stepsCompleted, unsigned int totalSteps){ if(progressBarMap.contains(timeStep)){ qCritical()<<"Attempting to add a progress bar for time step "<<timeStep<<" that already exists."; return; } //Progress bar QProgressBar* progBar = new QProgressBar(); progBar->setMinimumSize(100, 15); progBar->setBaseSize(100, 15); progBar->setRange(0, totalSteps); progBar->setValue(stepsCompleted); gridLayout->addWidget(new QLabel("Time step " + QString::number(timeStep) + ": "), progressBarMap.size(), 0); gridLayout->addWidget(progBar, progressBarMap.size(), 1); progressBarMap[timeStep] = progBar; //Progress details QLabel* progDetails = new QLabel(); progDetails->setMinimumSize(300, 15); progDetails->setBaseSize(300, 15); gridLayout->addWidget(progDetails, progressDetailsMap.size(), 2); progressDetailsMap[timeStep] = progDetails; }
/** Download all server contents */ bool ServerPackEditor::refreshServerContent() { if (serverManager()->serverCount() == 0) return true; if (d->_progressDialog) { delete d->_progressDialog; d->_progressDialog = 0; } d->_progressDialog = new QProgressDialog(this); QProgressBar *bar = new QProgressBar(d->_progressDialog); bar->setValue(0); bar->setRange(0, 0); d->_progressDialog->setBar(bar); d->_progressDialog->setLabelText(tr("Updating server information")); d->_progressDialog->setModal(true); d->_progressDialog->show(); connect(serverManager(), SIGNAL(allServerDescriptionAvailable()), this, SLOT(onRefreshServerDone()), Qt::UniqueConnection); // TODO: Connect the cancel button //connect(d->_progressDialog, SIGNAL(canceled()), &core(), SLOT(stopJobsAndClearQueues())); //connect(d->_progressDialog, SIGNAL(canceled()), d->_progressDialog, SLOT(deleteLater())); serverManager()->getAllDescriptionFile(bar); // dlg.exec(); return true; }
void PinDialog::init( PinFlags flags, const QString &title, TokenData::TokenFlags token ) { setMinimumWidth( 350 ); setWindowModality( Qt::ApplicationModal ); QLabel *label = new QLabel( this ); QVBoxLayout *l = new QVBoxLayout( this ); l->addWidget( label ); QString _title = title; QString text; if( token & TokenData::PinFinalTry ) text += "<font color='red'><b>" + tr("PIN will be locked next failed attempt") + "</b></font><br />"; else if( token & TokenData::PinCountLow ) text += "<font color='red'><b>" + tr("PIN has been entered incorrectly one time") + "</b></font><br />"; text += QString( "<b>%1</b><br />" ).arg( title ); if( flags & Pin2Type ) { _title = tr("Signing") + " - " + title; text += tr("Selected action requires sign certificate.") + "<br />" + (flags & PinpadFlag ? tr("For using sign certificate enter PIN2 with pinpad") : tr("For using sign certificate enter PIN2") ); regexp.setPattern( "\\d{5,12}" ); } else { _title = tr("Authendicating") + " - " + title; text += tr("Selected action requires auth certificate.") + "<br />" + (flags & PinpadFlag ? tr("For using auth certificate enter PIN1 with pinpad") : tr("For using auth certificate enter PIN1") ); regexp.setPattern( "\\d{4,12}" ); } setWindowTitle( _title ); label->setText( text ); if( flags & PinpadFlag ) { setWindowFlags( (windowFlags() | Qt::CustomizeWindowHint) & ~Qt::WindowCloseButtonHint ); QProgressBar *progress = new QProgressBar( this ); progress->setRange( 0, 30 ); progress->setValue( progress->maximum() ); progress->setTextVisible( false ); l->addWidget( progress ); QTimeLine *statusTimer = new QTimeLine( progress->maximum() * 1000, this ); statusTimer->setCurveShape( QTimeLine::LinearCurve ); statusTimer->setFrameRange( progress->maximum(), progress->minimum() ); connect( statusTimer, SIGNAL(frameChanged(int)), progress, SLOT(setValue(int)) ); connect( this, SIGNAL(startTimer()), statusTimer, SLOT(start()) ); } else { m_text = new QLineEdit( this ); m_text->setEchoMode( QLineEdit::Password ); m_text->setFocus(); m_text->setValidator( new QRegExpValidator( regexp, m_text ) ); connect( m_text, SIGNAL(textEdited(QString)), SLOT(textEdited(QString)) ); l->addWidget( m_text ); QDialogButtonBox *buttons = new QDialogButtonBox( QDialogButtonBox::Ok|QDialogButtonBox::Cancel, Qt::Horizontal, this ); ok = buttons->button( QDialogButtonBox::Ok ); ok->setAutoDefault( true ); connect( buttons, SIGNAL(accepted()), SLOT(accept()) ); connect( buttons, SIGNAL(rejected()), SLOT(reject()) ); l->addWidget( buttons ); textEdited( QString() ); } }
int main(int argc, char **argv) { int p = 0; toConfigurationNew::setQSettingsEnv(); QApplication app(argc, argv); qRegisterMetaType<toQColumnDescriptionList>("toQColumnDescriptionList&"); qRegisterMetaType<ValuesList>("ValuesList&"); qRegisterMetaType<toConnection::exception>("toConnection::exception"); try { toSplash splash(NULL); splash.show(); QList<QString> plugins; // List of all connection provider finders std::vector<std::string> finders = ConnectionProviderFinderFactory::Instance().keys(); // Resulting list of all the providers found toProvidersList &allProviders = toProvidersListSing::Instance(); QProgressBar *progress = splash.progress(); QLabel *label = splash.label(); progress->setRange(1, plugins.size() + finders.size()*2); qApp->processEvents(); Q_FOREACH(QString path, plugins) { label->setText(qApp->translate("main", "Loading plugin %1").arg(path)); qApp->processEvents(); bool success = false; try { QLibrary library(path); success = library.load(); } TOCATCH; if (success) { label->setText(qApp->translate("main", "Loaded plugin %1").arg(path)); TLOG(5, toDecoratorNC, __HERE__) << "Loaded plugin " << path << std::endl; } else { label->setText(qApp->translate("main", "Failed loading plugin %1").arg(path)); TLOG(5, toDecoratorNC, __HERE__) << "Failed loading plugin " << path << std::endl; } progress->setValue(progress->value()+1); qApp->processEvents(); } // Loop over all finders and call their "find" method, each of them can return several locations for (std::vector<std::string>::const_iterator i = finders.begin(); i != finders.end(); ++i) { QString finderName(i->c_str()); label->setText(qApp->translate("main", "Looking for %1").arg(finderName)); qApp->processEvents(); TLOG(5, toDecoratorNC, __HERE__) << "Looking for client: " << *i << std::endl; try { std::unique_ptr<toConnectionProviderFinder> finder = ConnectionProviderFinderFactory::Instance().create(*i, 0); QList<toConnectionProviderFinder::ConnectionProvirerParams> l = finder->find(); allProviders.append(l); finderName = finder->name(); } TOCATCH; progress->setValue(progress->value()+1); qApp->processEvents(); } // Loop over all providers found and try to load desired Oracle client // 1st try to load requested Oracle client(if set) then load thick(TNS) Oracle client QDir oHome = toConfigurationNewSingle::Instance().option(ToConfiguration::Global::OracleHomeDirectory).toString(); Q_FOREACH(toConnectionProviderFinder::ConnectionProvirerParams const& params, allProviders) { QString providerName = params.value("PROVIDER").toString(); if ( params.value("PROVIDER").toString() != ORACLE_PROVIDER) continue; QDir pHome(params.value("ORACLE_HOME").toString()); if (oHome != pHome) continue; try { label->setText(qApp->translate("main", "Loading provider %1").arg(providerName)); qApp->processEvents(); TLOG(5, toDecoratorNC, __HERE__) << "Loading: " << params.value("PATH").toString() << std::endl; toConnectionProviderRegistrySing::Instance().load(params); progress->setValue(progress->value()+1); qApp->processEvents(); break; } TOCATCH; }
/*! * \brief main * Guia de Trabajos Practicos 3 * \param argc * \param argv * \return */ int main(int argc, char *argv[]) { QApplication a( argc, argv ); QMainWindow main; a.connect( &a, SIGNAL(lastWindowClosed()), &a, SLOT(quit()) ); main.showMaximized(); QMdiArea *mdiArea = new QMdiArea; mdiArea->setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded); mdiArea->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded); main.setCentralWidget(mdiArea); GraficadorMdi *grafFuncion = new GraficadorMdi( mdiArea ); grafFuncion->setearTitulo( QString::fromUtf8( "Funcion" ) ); grafFuncion->setearTituloEjeX( QString::fromUtf8( "X" ) ); grafFuncion->setearTituloEjeY( QString::fromUtf8( "Y" ) ); mdiArea->addSubWindow( grafFuncion ); grafFuncion->show(); mdiArea->tileSubWindows(); GraficadorMdi *grafFitnes = new GraficadorMdi( mdiArea ); grafFitnes->setearTitulo( QString::fromUtf8( "Evolucion Mejor Fitness" ) ); grafFitnes->setearTituloEjeX( QString::fromUtf8( "Generacion" ) ); grafFitnes->setearTituloEjeY( QString::fromUtf8( "fitness" ) ); mdiArea->addSubWindow( grafFitnes ); grafFitnes->show(); mdiArea->tileSubWindows(); grafFitnes->setearParaSOM(); GraficadorMdi *grafPuntos = new GraficadorMdi( mdiArea ); grafPuntos->setearTitulo( QString::fromUtf8( "Puntos a evaluar" ) ); grafPuntos->setearTituloEjeX( QString::fromUtf8( "Posicion" ) ); grafPuntos->setearTituloEjeY( QString::fromUtf8( "Y" ) ); mdiArea->addSubWindow( grafPuntos ); grafPuntos->show(); mdiArea->tileSubWindows(); //grafPuntos->setearParaSOM(); // grafPuntos->setearEjesEnGrafico(); GraficadorMdi *grafPromedio = new GraficadorMdi( mdiArea ); grafPromedio->setearTitulo( QString::fromUtf8( "Fitness Promedio" ) ); grafPromedio->setearTituloEjeX( QString::fromUtf8( "Posicion" ) ); grafPromedio->setearTituloEjeY( QString::fromUtf8( "Y" ) ); mdiArea->addSubWindow( grafPromedio ); grafPromedio->show(); mdiArea->tileSubWindows(); grafPromedio->setearParaSOM(); // barra de progreso para mostrar el avance del tiempo QDockWidget *dockBarra = new QDockWidget( QString::fromUtf8( "Evaluaciones" ) ); main.addDockWidget( Qt::BottomDockWidgetArea, dockBarra ); QProgressBar *PBTiempo = new QProgressBar( dockBarra ); dockBarra->setWidget( PBTiempo ); //Inicializo con una semilla aleatoria para la generacion de Aleatorios qsrand( QTime::currentTime().msec() ); // Cargo los parametros del ejercicio QSettings parametros( "parametros.cfg", QSettings::IniFormat ); // Inicializo la poblacion Poblacion<GenomaX> pob; int cant_total = parametros.value( "cantidad_elementos" ).toInt(); pob.setearTotal( cant_total ); pob.setearElitismo( parametros.value( "elitismo", false ).toBool() ); pob.setearBrechaGeneracional( parametros.value( "brecha_generacional" ).toDouble() ); pob.setearProbabilidadMutacion( parametros.value( "probabilidad_mutacion").toDouble() ); pob.setearModoSeleccionPadres( (Poblacion<GenomaX>::MetodoSeleccion)parametros.value( "metodo_seleccion" ).toInt() ); pob.setearPorcentajeCantidadDePadres( parametros.value( "cantidad_padres" ).toDouble() ); double max = parametros.value( "max" ).toDouble(); double min = parametros.value( "min" ).toDouble(); pob.setearMinMax( min, max ); for( int i=0; i<cant_total; i++ ) { GenomaX temp; double valor = valor_random( min, max ); temp.setX( valor ); temp.setMinMax( min, max ); pob.append( temp ); } // Grafico la funcion QVector<double> posy, posx; for( double i=min; i<max; i+=0.05 ) { posx.append( i ); posy.append( evaluar( i ) ); } grafFuncion->agregarCurva( posx, posy, "funcion" ); a.processEvents(); /*GenomaX p1; p1.setX( 128.0 ); p1.mostrarGenotipo(); p1.mutar( 9 ); p1.mostrarGenotipo(); p1.mutar( 1 ); p1.mostrarGenotipo(); p1.mutar( 2 ); p1.mostrarGenotipo(); p1.mutar( 15 ); p1.mostrarGenotipo(); p1.mutar( 10 ); p1.mostrarGenotipo(); p1.mutar( 11 ); p1.mostrarGenotipo();*/ double fitnes_necesario = parametros.value( "fitnes_necesario", 0.0 ).toDouble(); int iteracciones_maximas = parametros.value( "iteracciones_maximas", 1000 ).toInt(); int iteracciones = 0; PBTiempo->setRange( 0, iteracciones_maximas ); pob.evaluarPoblacion(); a.processEvents(); QVector<double> histFitness; QVector<int> histIteracion; QVector<double> histPromFitnes; histFitness.append( pob.mejorFitnes() ); histIteracion.append( 0 ); histPromFitnes.append( pob.mejorFitnes() ); double mejor_fitness = 0.0; double pos_mejor_fitness = 0.0; int generacion_mejor_fitness = -1; while( pob.mejorFitnes() <= fitnes_necesario && iteracciones <= iteracciones_maximas ) { pob.seleccionarPadres(); a.processEvents(); pob.generarHijos(); a.processEvents(); pob.evaluarPoblacion(); a.processEvents(); iteracciones++; PBTiempo->setValue( iteracciones ); histFitness.append( pob.mejorFitnes() ); histIteracion.append( iteracciones ); grafFitnes->setearPuntos( histFitness, histIteracion ); a.processEvents(); QVector<double> x, y; double sumatoria = 0.0; for( int i=0; i<pob.size(); i++ ) { y.append( i ); x.append( pob.at( i ).getX() ); sumatoria += (-1.0)*evaluar( pob.at( i ).getX() ); } sumatoria /= pob.size(); histPromFitnes.append( sumatoria ); grafPuntos->agregarCurva( x, y, QString( "Gen%1" ).arg( iteracciones ) ); if( mejor_fitness <= pob.mejorFitnes() ) { mejor_fitness = pob.mejorFitnes(); pos_mejor_fitness = pob.elementoMinimo().getX(); generacion_mejor_fitness = iteracciones; } grafPromedio->setearPuntos( histPromFitnes, histIteracion ); } qDebug() << "Mejor Fitness: " << mejor_fitness; qDebug() << "Posicion Minimo: " << pos_mejor_fitness; qDebug() << "Minimo: " << evaluar( pos_mejor_fitness ); qDebug() << "Generacion: " << generacion_mejor_fitness; return a.exec(); }
void MetaEditorSupportPlugin::generateEditorWithQrmc() { qrmc::MetaCompiler metaCompiler(*mLogicalRepoApi, "."); IdList const metamodels = mLogicalRepoApi->children(Id::rootId()); QProgressBar *progress = new QProgressBar(mMainWindowInterface->windowWidget()); progress->show(); int const progressBarWidth = 240; int const progressBarHeight = 20; QApplication::processEvents(); QRect const screenRect = qApp->desktop()->availableGeometry(); progress->move(screenRect.width() / 2 - progressBarWidth / 2, screenRect.height() / 2 - progressBarHeight / 2); progress->setFixedWidth(progressBarWidth); progress->setFixedHeight(progressBarHeight); progress->setRange(0, 100); int forEditor = 60 / metamodels.size(); foreach (Id const &key, metamodels) { QString const objectType = key.element(); if (objectType == "MetamodelDiagram" && mLogicalRepoApi->isLogicalElement(key)) { QString nameOfTheDirectory = mLogicalRepoApi->stringProperty(key, "name of the directory"); QString nameOfMetamodel = mLogicalRepoApi->stringProperty(key, "name"); QString nameOfPlugin = nameOfTheDirectory.split("/").last(); if (QMessageBox::question(mMainWindowInterface->windowWidget() , tr("loading..") , QString(tr("Do you want to compile and load editor %1?")).arg(nameOfPlugin) , QMessageBox::Yes, QMessageBox::No) == QMessageBox::No) { continue; } progress->setValue(5); const QString normalizedName = nameOfMetamodel.at(0).toUpper() + nameOfMetamodel.mid(1); const bool stateOfLoad = mMainWindowInterface->pluginLoaded(normalizedName); if (!mMainWindowInterface->unloadPlugin(normalizedName)) { progress->close(); delete progress; return; } if (!metaCompiler.compile(nameOfMetamodel)) { // generating source code for all metamodels QMessageBox::warning(mMainWindowInterface->windowWidget() , tr("error") , tr("Cannot generate source code for editor ") + nameOfPlugin); continue; } progress->setValue(20); QStringList qmakeArgs; qmakeArgs.append("CONFIG+=" + mLogicalRepoApi->stringProperty(key, "buildConfiguration")); qmakeArgs.append(nameOfMetamodel + ".pro"); QProcess builder; builder.setWorkingDirectory(nameOfTheDirectory); const QStringList environment = QProcess::systemEnvironment(); builder.setEnvironment(environment); builder.start(SettingsManager::value("pathToQmake").toString(), qmakeArgs); qDebug() << "qmake"; if ((builder.waitForFinished()) && (builder.exitCode() == 0)) { progress->setValue(40); builder.start(SettingsManager::value("pathToMake").toString()); bool finished = builder.waitForFinished(100000); qDebug() << "make"; if (finished && (builder.exitCode() == 0)) { if (stateOfLoad) { QMessageBox::warning(mMainWindowInterface->windowWidget() , tr("Attention!"), tr("Please restart QReal.")); progress->close(); delete progress; return; } qDebug() << "make ok"; progress->setValue(progress->value() + forEditor / 2); if (!nameOfMetamodel.isEmpty()) { if (!mMainWindowInterface->unloadPlugin(normalizedName)) { QMessageBox::warning(mMainWindowInterface->windowWidget() , tr("error") , tr("cannot unload plugin ") + normalizedName); progress->close(); delete progress; continue; } } QString suffix = ""; if (mLogicalRepoApi->stringProperty(key, "buildConfiguration") == "debug") { suffix = "-d"; } QString const generatedPluginFileName = SettingsManager::value("prefix").toString() + nameOfMetamodel + suffix + "." + SettingsManager::value("pluginExtension").toString() ; if (mMainWindowInterface->loadPlugin(generatedPluginFileName, normalizedName)) { progress->setValue(progress->value() + forEditor / 2); } } progress->setValue(100); } } }
MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); ui->textBrowser->setFont(QFont("Monospace",11)); ui->textBrowser->setLineWrapMode(QTextEdit::NoWrap); updater->moveToThread(pthread); fileTotal->moveToThread(fthread); //User selects directory, or action connect(this,SIGNAL(userSelect(QString)),updater,SLOT(action(QString))); connect(this,SIGNAL(selectDir(QString)),updater,SLOT(selectDir(QString))); connect(this,SIGNAL(selectDir(QString)),fileTotal,SLOT(selectDir(QString))); //Returning from Worker Thread connect(updater,SIGNAL(Finished(QString)),this,SLOT(action(QString))); //Clean up threads connect(updater,SIGNAL(close()),pthread,SLOT(quit())); connect(pthread, SIGNAL(finished()), updater, SLOT(deleteLater())); connect(fileTotal,SIGNAL(close()),fthread,SLOT(quit())); connect(fthread,SIGNAL(finished()),fileTotal,SLOT(deleteLater())); //Start Thread(s) pthread->start(); fthread->start(); //Get number of files in directory for progress bar //connect(this,SIGNAL(getfileTotal()),updater,SLOT(getfileTotal())); connect(this,SIGNAL(getfileTotal(QString)),fileTotal,SLOT(getfileTotal(QString))); //request from main thread connect(fileTotal,SIGNAL(finished(int)),updater,SLOT(getfileTotal(int))); //transfer total from getfiletotal object to worker object connect(updater,SIGNAL(getfileTotal(QString)),fileTotal,SLOT(getfileTotal(QString))); //request from updater connect(updater,SIGNAL(displayFileTotal(int)),this,SLOT(displayFileTotal(int))); connect(fileTotal,SIGNAL(finished(int)),this,SLOT(enableButton())); //Create ProgressBar QProgressBar *bar = new QProgressBar(ui->statusBar); ui->statusBar->addWidget(bar); bar->setRange(0,100); bar->setValue(0); bar->hide(); connect(updater,SIGNAL(percentChanged(int)),bar,SLOT(setValue(int))); connect(updater,SIGNAL(percentChanged(int)),bar,SLOT(show())); connect(this,SIGNAL(hidebar()),bar,SLOT(hide())); //fileTotal->getfileTotal(); emit getfileTotal(dirSelect); ui->pushButton->setEnabled(false); //TABLE FUNZ QShortcut *shortcut = new QShortcut(QKeySequence("Ctrl+C"), this); connect(shortcut,SIGNAL(activated()),this,SLOT(on_actionCopy_triggered())); // ui->tableWidget->setColumnCount(3); // ui->tableWidget->setRowCount(100); // ui->tableWidget->setHorizontalHeaderLabels(QStringList() << "File" << "Hash" << "Check"); // ui->tableWidget->horizontalHeader()->setStretchLastSection(true); // ui->tableWidget->horizontalHeader()->setSectionResizeMode(1,QHeaderView::Stretch); }
QWidget* WidgetStyle::createWidget(const QString& name) { if(name == "CheckBox") { QCheckBox* box = new QCheckBox("CheckBox"); box->setObjectName("CheckBox"); return setLayoutWidget({ box }, { 100, 30 }); } else if(name == "ComboBox") { QComboBox* box = new QComboBox; box->addItem("Item1"); box->addItem("Item3"); box->addItem("Item3"); box->setObjectName("ComboBox"); return setLayoutWidget({ box }, { 70, 30 }); } else if(name == "DateEdit") { QDateEdit* date = new QDateEdit; date->setObjectName("DateEdit"); return setLayoutWidget({ date }, { 110, 40 }); } else if(name == "DateTimeEdit") { QDateTimeEdit* date = new QDateTimeEdit; date->setObjectName("DateTimeEdit"); return setLayoutWidget({ date }, { 160, 30 }); } else if(name == "Dialog") { QDialog* dialog = new QDialog; dialog->setObjectName("Dialog"); return setLayoutWidget({ dialog }, { 160, 110 }); } else if(name == "DockWidget") //? { QDockWidget* widget = new QDockWidget; widget->setObjectName("DockWidget"); widget->resize(61, 22); return widget; } else if(name == "DoubleSpinBox") { QDoubleSpinBox* box = new QDoubleSpinBox; box->setObjectName("DoubleSpinBox"); return setLayoutWidget({ box }, { 90, 40 }); } else if(name == "Frame") //?? { QFrame* frame = new QFrame; frame->setObjectName("Frame"); frame->resize(150, 100); return frame; } else if(name == "GroupBox") { QGroupBox* box = new QGroupBox("GroupBox"); box->setObjectName("GroupBox"); return setLayoutWidget({ box }, { 160, 110 }); } else if(name == "Label") { QLabel* label = new QLabel("Label"); label->setObjectName("Label"); return setLayoutWidget({ label }, { 40, 20}); } else if(name == "LineEdit") { QLineEdit* line = new QLineEdit; line->setObjectName("LineEdit"); return setLayoutWidget({ line }, { 30, 30 }); } else if(name == "ListView") //?? { QListView* view = new QListView; view->setObjectName("ListView"); view->resize(71, 71); return view; } else if(name == "ListWidget") { QListWidget* list = new QListWidget; list->setObjectName("ListWidget"); for(int i = 0; i < 20; i++) list->addItem(QString("Item %1").arg(i)); return setLayoutWidget({ list }, { 80, 80 }); } else if(name == "MainWindow") { QMainWindow* window = new QMainWindow; window->setObjectName("MainWindow"); return setLayoutWidget({ window }, { 160, 110 }); } else if(name == "Menu") { QMenu* parentMenu = new QMenu; parentMenu->setObjectName("Menu"); parentMenu->addMenu("Menu1"); QMenu* menu1 = parentMenu->addMenu("Menu2"); menu1->addMenu("Menu1"); menu1->addMenu("Menu2"); parentMenu->addSeparator(); parentMenu->addMenu("Menu3"); return setLayoutWidget({ parentMenu }, { 160, 110 }); } else if(name == "MenuBar") { QMenuBar* bar = new QMenuBar; bar->setObjectName("QMenuBar"); QMenu* menu1 = bar->addMenu("MenuBar1"); menu1->addMenu("Menu1"); menu1->addSeparator(); menu1->addMenu("Menu2"); QMenu* menu2 = bar->addMenu("MenuBar2"); menu2->addMenu("Menu1"); menu2->addSeparator(); menu2->addMenu("Menu2"); QMenu* menu3 = bar->addMenu("MenuBar3"); menu3->addMenu("Menu1"); menu3->addSeparator(); menu3->addMenu("Menu2"); return setLayoutWidget({ bar }, { 280, 60 }); } else if(name == "ProgressBar") { QProgressBar* bar = new QProgressBar; bar->setObjectName("ProgressBar"); bar->setRange(0, 100); bar->setValue(0); QTimer* timer = new QTimer(bar); this->connect(timer, &QTimer::timeout, this, [bar]() { if(bar->value() == 100) bar->setValue(0); else bar->setValue(bar->value() + 1); }); timer->start(100); return setLayoutWidget({ bar }, { 110, 30 }); } else if(name == "PushButton") { QPushButton* button = new QPushButton("PushButton"); button->setObjectName("PushButton"); return setLayoutWidget({ button }, { 125, 30 }); } else if(name == "RadioButton") { QRadioButton* button = new QRadioButton("RadioButton"); button->setObjectName("RadioButton"); return setLayoutWidget({ button }, { 125, 30 }); } else if(name == "ScrollBar") { QScrollBar* barH = new QScrollBar(Qt::Horizontal); QScrollBar* barV = new QScrollBar(Qt::Vertical); barH->setObjectName("ScrollBarH"); barV->setObjectName("ScrollBarV"); return setLayoutWidget({ barH, barV }, { 200, 100 }); } else if(name == "Slider") { QSlider* sliderH = new QSlider(Qt::Horizontal); QSlider* sliderV = new QSlider(Qt::Vertical); sliderH->setObjectName("SliderH"); sliderV->setObjectName("SliderV"); return setLayoutWidget({ sliderH, sliderV }, { 200, 100 }); } else if(name == "SpinBox") { QSpinBox* spinBox = new QSpinBox; spinBox->setObjectName("SpinBox"); return setLayoutWidget({ spinBox }, { 60, 35 }); } else if(name == "Splitter") { QSplitter* splitterV = new QSplitter(Qt::Vertical); QSplitter* splitterH = new QSplitter(Qt::Horizontal); splitterV->setObjectName("SplitterV"); splitterH->setObjectName("SplitterH"); splitterV->addWidget(new QPushButton("PushButton1")); splitterV->addWidget(new QPushButton("PushButton2")); splitterH->addWidget(splitterV); splitterH->addWidget(new QPushButton("PushButton3")); return setLayoutWidget({ splitterH }, { 250, 110 }); } else if(name == "TabWidget") { QTabWidget* tab = new QTabWidget; tab->addTab(new QWidget, "Widget1"); tab->addTab(new QWidget, "Widget2"); tab->addTab(new QWidget, "Widget3"); tab->setObjectName("TabWidget"); return setLayoutWidget({ tab }, { 210, 110 }); } else if(name == "TableView") //? { QTableView* view = new QTableView; view->setObjectName("TableView"); view->resize(200, 100); return view; } else if(name == "TableWidget") { const int n = 100; QStringList list = { "one", "two", "three" }; QTableWidget* table = new QTableWidget(n, n); table->setObjectName("TableWidget"); table->setHorizontalHeaderLabels(list); table->setVerticalHeaderLabels(list); for(int i = 0; i < n; i++) for(int j = 0; j < n; j++) table->setItem(i, j, new QTableWidgetItem(QString("%1, %2").arg(i).arg(j))); return setLayoutWidget({ table }, { 210, 110 }); } else if(name == "TextEdit") { QTextEdit* text = new QTextEdit; text->setObjectName("TextEdit"); return setLayoutWidget({ text }, { 80, 80 }); } else if(name == "TimeEdit") { QTimeEdit* time = new QTimeEdit; time->setObjectName("TimeEdit"); return setLayoutWidget({ time }, { 80, 80 }); } else if(name == "ToolButton") { QToolButton* button = new QToolButton; button->setText("ToolButton"); button->setObjectName("ToolButton"); return setLayoutWidget({ button }, { 95, 25 }); } else if(name == "ToolBox") { QToolBox* box = new QToolBox; box->addItem(new QWidget, "Widget1"); box->addItem(new QWidget, "Widget2"); box->addItem(new QWidget, "Widget3"); box->setObjectName("ToolBox"); return setLayoutWidget({ box }, { 110, 180 }); } else if(name == "TreeView") //? { QTreeView* tree = new QTreeView; tree->setObjectName("TreeView"); tree->resize(200, 100); return tree; } else if(name == "TreeWidget") { QTreeWidget* tree = new QTreeWidget; tree->setObjectName("TreeWidget"); tree->setHeaderLabels({ "Folders", "Used Space" }); QTreeWidgetItem* item = new QTreeWidgetItem(tree); item->setText(0, "Local Disk"); for(int i = 1; i < 20; i++) { QTreeWidgetItem* dir = new QTreeWidgetItem(item); dir->setText(0, "Directory" + QString::number(i)); dir->setText(1, QString::number(i) + "MB"); } tree->setItemExpanded(item, true); return setLayoutWidget({ tree }, { 210, 110 }); } else if(name == "Widget") { QWidget* widget = new QWidget; widget->setObjectName("Widget"); return setLayoutWidget({ widget }, { 210, 110 }); } return nullptr; }
void MolTableView::setMol( adchem::SDFile& file, QProgressBar& progressBar ) { if ( file ) { adcontrols::ChemicalFormula cformula; qtwrapper::waitCursor wait; //RDKit::SDMolSupplier& supplier = file.molSupplier(); model_->setRowCount( file.size() ); progressBar.setRange( 0, file.size() ); progressBar.setVisible( true ); progressBar.setTextVisible( true ); size_t idx = 0; for ( auto mol: file ) { progressBar.setValue( idx + 1 ); try { size_t col = 0; std::string smiles = RDKit::MolToSmiles( mol ); if ( ! smiles.empty() ) { model_->setData( model_->index( idx, col++ ), smiles.c_str() ); // SVG std::string svg = adchem::drawing::toSVG( mol ); model_->setData( model_->index( idx, col ), QByteArray( svg.data(), svg.size() ) ); model_->item( idx, col )->setEditable( false ); } col = 2; try { mol.updatePropertyCache( false ); std::string formula = RDKit::Descriptors::calcMolFormula( mol, true, false ); model_->setData( model_->index( idx, col++ ), QString::fromStdString( formula) ); model_->setData( model_->index( idx, col++), cformula.getMonoIsotopicMass( formula ) ); } catch ( std::exception& ex ) { ADDEBUG() << ex.what(); } col = 4; // associated data std::map< std::string, std::string > data; adchem::SDFile::iterator it = file.begin() + idx; if ( adchem::SDFile::parseItemText( it.itemText(), data ) ) { for ( auto tag: tags ) { auto it = data.find( tag ); if ( it != data.end() ) model_->setData( model_->index( idx, col ), it->second.c_str() ); ++col; } } if ( idx == 10 ) this->update(); } catch ( std::exception& ex ) { ADDEBUG() << boost::current_exception_diagnostic_information() << ex.what(); } catch ( ... ) { ADDEBUG() << boost::current_exception_diagnostic_information(); } ++idx; } progressBar.setVisible( false ); } }
void BackupDialog::restore() { // Get last backup folder: KConfig *config = KGlobal::config().data(); KConfigGroup configGroup(config, "Backups"); QString folder = configGroup.readEntry("lastFolder", QDir::homePath()) + "/"; // Ask a file name to the user: QString filter = "*.tar.gz|" + i18n("Tar Archives Compressed by Gzip") + "\n*|" + i18n("All Files"); QString path = KFileDialog::getOpenFileName(folder, filter, this, i18n("Open Basket Archive")); if (path.isEmpty()) // User has canceled return; // Before replacing the basket data folder with the backup content, we safely backup the current baskets to the home folder. // So if the backup is corrupted or something goes wrong while restoring (power cut...) the user will be able to restore the old working data: QString safetyPath = Backup::newSafetyFolder(); FormatImporter copier; copier.moveFolder(Global::savesFolder(), safetyPath); // Add the README file for user to cancel a bad restoration: QString readmePath = safetyPath + i18n("README.txt"); QFile file(readmePath); if (file.open(QIODevice::WriteOnly)) { QTextStream stream(&file); stream << i18n("This is a safety copy of your baskets like they were before you started to restore the backup %1.", KUrl(path).fileName()) + "\n\n" << i18n("If the restoration was a success and you restored what you wanted to restore, you can remove this folder.") + "\n\n" << i18n("If something went wrong during the restoration process, you can re-use this folder to store your baskets and nothing will be lost.") + "\n\n" << i18n("Choose \"Basket\" -> \"Backup & Restore...\" -> \"Use Another Existing Folder...\" and select that folder.") + "\n"; file.close(); } QString message = "<p><nobr>" + i18n("Restoring <b>%1</b>. Please wait...", KUrl(path).fileName()) + "</nobr></p><p>" + i18n("If something goes wrong during the restoration process, read the file <b>%1</b>.", readmePath); KProgressDialog *dialog = new KProgressDialog(0, i18n("Restore Baskets"), message); dialog->setModal(/*modal=*/true); dialog->setAllowCancel(false); dialog->setAutoClose(true); dialog->show(); QProgressBar *progress = dialog->progressBar(); progress->setRange(0, 0/*Busy/Undefined*/); progress->setValue(0); progress->setTextVisible(false); // Uncompress: RestoreThread thread(path, Global::savesFolder()); thread.start(); while (thread.isRunning()) { progress->setValue(progress->value() + 1); // Or else, the animation is not played! kapp->processEvents(); usleep(300); // Not too long because if the restore process is finished, we wait for nothing } dialog->hide(); // The restore is finished, do not continue to show it while telling the user the application is going to be restarted delete dialog; // If we only hidden it, it reappeared just after having restored a small backup... Very strange. dialog = 0; // This was annoying since it is modal and the "BasKet Note Pads is going to be restarted" message was not reachable. //kapp->processEvents(); // Check for errors: if (!thread.success()) { // Restore the old baskets: QDir dir; dir.remove(readmePath); copier.moveFolder(safetyPath, Global::savesFolder()); // Tell the user: KMessageBox::error(0, i18n("This archive is either not a backup of baskets or is corrupted. It cannot be imported. Your old baskets have been preserved instead."), i18n("Restore Error")); return; } // Note: The safety backup is not removed now because the code can has been wrong, somehow, or the user perhapse restored an older backup by error... // The restore process will not be called very often (it is possible it will only be called once or twice arround the world during the next years). // So it is rare enough to force the user to remove the safety folder, but keep him in control and let him safely recover from restoration errors. Backup::setFolderAndRestart(Global::savesFolder()/*No change*/, i18n("Your backup has been successfuly restored to <b>%1</b>. %2 is going to be restarted to take this change into account.")); }
MainWindow::MainWindow() : mUi(new Ui::MainWindowUi()) , mListenerManager(NULL) , mPropertyModel(NULL) { QSettings settings("SPbSU", "QReal"); //bool showSplash = settings.value("Splashscreen", true).toBool(); bool showSplash = false; QSplashScreen* splash = new QSplashScreen(QPixmap(":/icons/kroki3.PNG"), Qt::SplashScreen | Qt::WindowStaysOnTopHint); QProgressBar *progress = new QProgressBar((QWidget*) splash); progress->move(20,270); progress->setFixedWidth(600); progress->setFixedHeight(15); progress->setRange(0, 100); // Step 1: splash screen loaded, progress bar initialized. progress->setValue(5); if (showSplash) { splash->show(); QApplication::processEvents(); } mUi->setupUi(this); #if defined(Q_WS_WIN) mUi->menuSvn->setEnabled(false); // Doesn't work under Windows anyway. #endif mUi->tabs->setTabsClosable(true); mUi->tabs->setMovable(true); if (!showSplash) mUi->actionShowSplash->setChecked(false); mUi->minimapView->setRenderHint(QPainter::Antialiasing, true); // Step 2: Ui is ready, splash screen shown. progress->setValue(20); mUi->actionShow_grid->setChecked(settings.value("ShowGrid", true).toBool()); mUi->actionShow_alignment->setChecked(settings.value("ShowAlignment", true).toBool()); mUi->actionSwitch_on_grid->setChecked(settings.value("ActivateGrid", false).toBool()); mUi->actionSwitch_on_alignment->setChecked(settings.value("ActivateAlignment", true).toBool()); connect(mUi->actionQuit, SIGNAL(triggered()), this, SLOT(close())); connect(mUi->actionShowSplash, SIGNAL(toggled(bool)), this, SLOT (toggleShowSplash(bool))); connect(mUi->actionOpen, SIGNAL(triggered()), this, SLOT(open())); connect(mUi->actionSave, SIGNAL(triggered()), this, SLOT(saveAll())); connect(mUi->actionSave_as, SIGNAL(triggered()), this, SLOT(saveAs())); connect(mUi->actionPrint, SIGNAL(triggered()), this, SLOT(print())); connect(mUi->actionMakeSvg, SIGNAL(triggered()), this, SLOT(makeSvg())); connect(mUi->actionDeleteFromDiagram, SIGNAL(triggered()), this, SLOT(deleteFromDiagram())); connect(mUi->tabs, SIGNAL(currentChanged(int)), this, SLOT(changeMiniMapSource(int))); connect(mUi->tabs, SIGNAL(tabCloseRequested(int)), this, SLOT(closeTab(int))); connect(mUi->actionCheckout, SIGNAL(triggered()), this, SLOT(doCheckout())); connect(mUi->actionCommit, SIGNAL(triggered()), this, SLOT(doCommit())); connect(mUi->actionExport_to_XMI, SIGNAL(triggered()), this, SLOT(exportToXmi())); connect(mUi->actionGenerate_to_Java, SIGNAL(triggered()), this, SLOT(generateToJava())); connect(mUi->actionGenerate_to_Hascol, SIGNAL(triggered()), this, SLOT(generateToHascol())); connect(mUi->actionShape_Edit, SIGNAL(triggered()), this, SLOT(openShapeEditor())); connect(mUi->actionGenerate_Editor, SIGNAL(triggered()), this, SLOT(generateEditor())); connect(mUi->actionGenerate_Editor_qrmc, SIGNAL(triggered()), this, SLOT(generateEditorWithQRMC())); connect(mUi->actionParse_Editor_xml, SIGNAL(triggered()), this, SLOT(parseEditorXml())); connect(mUi->actionPreferences, SIGNAL(triggered()), this, SLOT(showPreferencesDialog())); connect(mUi->actionParse_Hascol_sources, SIGNAL(triggered()), this, SLOT(parseHascol())); connect(mUi->actionParse_Java_Libraries, SIGNAL(triggered()), this, SLOT(parseJavaLibraries())); connect(mUi->actionPlugins, SIGNAL(triggered()), this, SLOT(settingsPlugins())); connect(mUi->actionShow_grid, SIGNAL(toggled(bool)), this, SLOT(showGrid(bool))); connect(mUi->actionShow_alignment, SIGNAL(toggled(bool)), this, SLOT(showAlignment(bool))); connect(mUi->actionSwitch_on_grid, SIGNAL(toggled(bool)), this, SLOT(switchGrid(bool))); connect(mUi->actionSwitch_on_alignment, SIGNAL(toggled(bool)), this, SLOT(switchAlignment(bool))); connect(mUi->actionHelp, SIGNAL(triggered()), this, SLOT(showHelp())); connect(mUi->actionAbout, SIGNAL(triggered()), this, SLOT(showAbout())); connect(mUi->actionAboutQt, SIGNAL(triggered()), qApp, SLOT(aboutQt())); connect(mUi->actionShow, SIGNAL(triggered()), this, SLOT(showGestures())); connect(mUi->minimapZoomSlider, SIGNAL(valueChanged(int)), this, SLOT(adjustMinimapZoom(int))); connect(mUi->actionDebug, SIGNAL(triggered()), this, SLOT(debug())); connect(mUi->actionDebug_Single_step, SIGNAL(triggered()), this, SLOT(debugSingleStep())); connect(mUi->actionClear, SIGNAL(triggered()), this, SLOT(exterminate())); connect(mUi->save_metamodel, SIGNAL(triggered()), this, SLOT(saveMetaModel())); adjustMinimapZoom(mUi->minimapZoomSlider->value()); initGridProperties(); // Step 3: Ui connects are done. progress->setValue(40); QString workingDir = settings.value("workingDir", ".").toString(); mRootIndex = QModelIndex(); mModels = new models::Models(workingDir, mEditorManager); mPropertyModel = new PropertyEditorModel(mEditorManager, mModels->logicalModelAssistApi()); mUi->paletteDock->setWidget(mUi->paletteToolbox); mUi->errorDock->setWidget(mUi->errorListWidget); mUi->errorListWidget->init(this); mUi->errorDock->setVisible(false); mUi->propertyEditor->setModel(mPropertyModel); mUi->propertyEditor->verticalHeader()->hide(); mUi->propertyEditor->horizontalHeader()->setResizeMode(0, QHeaderView::ResizeToContents); mUi->propertyEditor->horizontalHeader()->setResizeMode(1, QHeaderView::Stretch); mUi->propertyEditor->setItemDelegate(&mDelegate); connect(mUi->graphicalModelExplorer, SIGNAL(clicked(QModelIndex const &)), this, SLOT(graphicalModelExplorerClicked(QModelIndex))); connect(mUi->logicalModelExplorer, SIGNAL(clicked(QModelIndex const &)), this, SLOT(logicalModelExplorerClicked(QModelIndex))); mUi->graphicalModelExplorer->addAction(mUi->actionDeleteFromDiagram); mUi->logicalModelExplorer->addAction(mUi->actionDeleteFromDiagram); // Step 4: Property editor and model explorers are initialized. progress->setValue(60); loadPlugins(); showMaximized(); // Step 5: Plugins are loaded. progress->setValue(70); settings.beginGroup("MainWindow"); if (!settings.value("maximized", true).toBool()) { showNormal(); resize(settings.value("size", QSize(1024, 800)).toSize()); move(settings.value("pos", QPoint(0, 0)).toPoint()); } settings.endGroup(); // Step 6: Save loaded, models initialized. progress->setValue(80); mListenerManager = new ListenerManager(mEditorManager.listeners() , mModels->logicalModelAssistApi(), mModels->graphicalModelAssistApi()); TypeList missingPlugins = mEditorManager.checkNeededPlugins(mModels->logicalRepoApi(), mModels->graphicalRepoApi()); if (!missingPlugins.isEmpty()) { QString text = "These plugins are not present, but needed to load the save:\n"; foreach (NewType const type, missingPlugins) { text += type.editor() + "\n"; QMessageBox::warning(this, tr("Some plugins are missing"), text); close(); return; }