• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

C++ QFile函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了C++中QFile函数的典型用法代码示例。如果您正苦于以下问题:C++ QFile函数的具体用法?C++ QFile怎么用?C++ QFile使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了QFile函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C++代码示例。

示例1: LOG

void UpdateChecker::unpackUpdate() {
	QByteArray packed;
	if (!outputFile.open(QIODevice::ReadOnly)) {
		LOG(("Update Error: cant read updates file!"));
		return fatalFail();
	}

#ifdef Q_OS_WIN // use Lzma SDK for win
	const int32 hSigLen = 128, hShaLen = 20, hPropsLen = LZMA_PROPS_SIZE, hOriginalSizeLen = sizeof(int32), hSize = hSigLen + hShaLen + hPropsLen + hOriginalSizeLen; // header
#else // Q_OS_WIN
	const int32 hSigLen = 128, hShaLen = 20, hPropsLen = 0, hOriginalSizeLen = sizeof(int32), hSize = hSigLen + hShaLen + hOriginalSizeLen; // header
#endif // Q_OS_WIN

	QByteArray compressed = outputFile.readAll();
	int32 compressedLen = compressed.size() - hSize;
	if (compressedLen <= 0) {
		LOG(("Update Error: bad compressed size: %1").arg(compressed.size()));
		return fatalFail();
	}
	outputFile.close();

	QString tempDirPath = cWorkingDir() + qsl("tupdates/temp"), readyFilePath = cWorkingDir() + qsl("tupdates/temp/ready");
	psDeleteDir(tempDirPath);

	QDir tempDir(tempDirPath);
	if (tempDir.exists() || QFile(readyFilePath).exists()) {
		LOG(("Update Error: cant clear tupdates/temp dir!"));
		return fatalFail();
	}

	uchar sha1Buffer[20];
	bool goodSha1 = !memcmp(compressed.constData() + hSigLen, hashSha1(compressed.constData() + hSigLen + hShaLen, compressedLen + hPropsLen + hOriginalSizeLen, sha1Buffer), hShaLen);
	if (!goodSha1) {
		LOG(("Update Error: bad SHA1 hash of update file!"));
		return fatalFail();
	}

	RSA *pbKey = PEM_read_bio_RSAPublicKey(BIO_new_mem_buf(const_cast<char*>(AppAlphaVersion ? UpdatesPublicAlphaKey : UpdatesPublicKey), -1), 0, 0, 0);
	if (!pbKey) {
		LOG(("Update Error: cant read public rsa key!"));
		return fatalFail();
	}
	if (RSA_verify(NID_sha1, (const uchar*)(compressed.constData() + hSigLen), hShaLen, (const uchar*)(compressed.constData()), hSigLen, pbKey) != 1) { // verify signature
		RSA_free(pbKey);
		if (cAlphaVersion() || cBetaVersion()) { // try other public key, if we are in alpha or beta version
			pbKey = PEM_read_bio_RSAPublicKey(BIO_new_mem_buf(const_cast<char*>(AppAlphaVersion ? UpdatesPublicKey : UpdatesPublicAlphaKey), -1), 0, 0, 0);
			if (!pbKey) {
				LOG(("Update Error: cant read public rsa key!"));
				return fatalFail();
			}
			if (RSA_verify(NID_sha1, (const uchar*)(compressed.constData() + hSigLen), hShaLen, (const uchar*)(compressed.constData()), hSigLen, pbKey) != 1) { // verify signature
				RSA_free(pbKey);
				LOG(("Update Error: bad RSA signature of update file!"));
				return fatalFail();
			}
		} else {
			LOG(("Update Error: bad RSA signature of update file!"));
			return fatalFail();
		}
	}
	RSA_free(pbKey);

	QByteArray uncompressed;

	int32 uncompressedLen;
	memcpy(&uncompressedLen, compressed.constData() + hSigLen + hShaLen + hPropsLen, hOriginalSizeLen);
	uncompressed.resize(uncompressedLen);

	size_t resultLen = uncompressed.size();
#ifdef Q_OS_WIN // use Lzma SDK for win
	SizeT srcLen = compressedLen;
	int uncompressRes = LzmaUncompress((uchar*)uncompressed.data(), &resultLen, (const uchar*)(compressed.constData() + hSize), &srcLen, (const uchar*)(compressed.constData() + hSigLen + hShaLen), LZMA_PROPS_SIZE);
	if (uncompressRes != SZ_OK) {
		LOG(("Update Error: could not uncompress lzma, code: %1").arg(uncompressRes));
		return fatalFail();
	}
#else // Q_OS_WIN
	lzma_stream stream = LZMA_STREAM_INIT;

	lzma_ret ret = lzma_stream_decoder(&stream, UINT64_MAX, LZMA_CONCATENATED);
	if (ret != LZMA_OK) {
		const char *msg;
		switch (ret) {
		case LZMA_MEM_ERROR: msg = "Memory allocation failed"; break;
		case LZMA_OPTIONS_ERROR: msg = "Specified preset is not supported"; break;
		case LZMA_UNSUPPORTED_CHECK: msg = "Specified integrity check is not supported"; break;
		default: msg = "Unknown error, possibly a bug"; break;
		}
		LOG(("Error initializing the decoder: %1 (error code %2)").arg(msg).arg(ret));
		return fatalFail();
	}

	stream.avail_in = compressedLen;
	stream.next_in = (uint8_t*)(compressed.constData() + hSize);
	stream.avail_out = resultLen;
	stream.next_out = (uint8_t*)uncompressed.data();

	lzma_ret res = lzma_code(&stream, LZMA_FINISH);
	if (stream.avail_in) {
		LOG(("Error in decompression, %1 bytes left in _in of %2 whole.").arg(stream.avail_in).arg(compressedLen));
//.........这里部分代码省略.........
开发者ID:2asoft,项目名称:tdesktop,代码行数:101,代码来源:autoupdater.cpp


示例2: dialog

void IconSettings::cmdGetIcon_Click(){
    QString fileName, searchPath=this->prefix_path;

    if ((!txtWorkDir->text().isEmpty()) and (QDir(txtWorkDir->text()).exists())){
        searchPath = txtWorkDir->text();
    } else {
        if (QDir(this->prefix_path).exists()){
           searchPath=this->prefix_path;
        } else {
           searchPath=QDir::homePath();
        }
    }

    QFileDialog dialog(this);
      dialog.setFilter(QDir::Dirs | QDir::Files | QDir::Hidden);
      dialog.setFileMode(QFileDialog::ExistingFile);
      dialog.setWindowTitle(tr("Open image file"));

#if QT_VERSION >= 0x040500
      if (CoreLib->getSetting("advanced", "useNativeFileDialog", false, 1)==0){
          dialog.setOptions(QFileDialog::DontUseNativeDialog);
      }
#endif

      if ((!iconPath.isEmpty()) and (QFile(iconPath).exists())){
          QStringList list = iconPath.split("/");
          searchPath = iconPath.left(iconPath.length() - list.last().length());
      }
      dialog.setDirectory(searchPath);

        #ifndef WITH_ICOUTILS
        dialog.setNameFilter(tr("Image files (*.png *.jpg *.gif *.bmp *.xpm)"));
        #else
        dialog.setNameFilter(tr("Image and Win32 binary files (*.png *.jpg *.gif *.bmp *.xpm *.exe *.dll);;Image files (*.png *.jpg *.gif *.bmp *.xpm);;Win32 Executable (*.exe);;Win32 Shared libraies (*.dll);;Win32 Executable and Shared libraies (*.exe *.dll)"));
        #endif
      //dialog.setSidebarUrls(add_prefix_urls);

     if (dialog.exec())
        fileName = dialog.selectedFiles().first();

    if(!fileName.isEmpty()){
        if ((fileName.toLower().right(3)!="exe") && (fileName.toLower().right(3)!="dll")){
            cmdGetIcon->setIcon (QIcon(fileName));
        } else {

            QStringList args;
            args << "-x";
            args << "-t" << "14";

            QString tmpDir="";
            QStringList list1 = fileName.split("/");

            tmpDir.append(QDir::homePath());
            tmpDir.append("/.config/");
            tmpDir.append(APP_SHORT_NAME);
            tmpDir.append("/tmp/");
            tmpDir.append(list1.last());

            QDir tmp(tmpDir);
            tmp.setFilter(QDir::Files | QDir::Hidden | QDir::NoSymLinks);
            QFileInfoList list = tmp.entryInfoList();

            if (tmp.exists(tmpDir)){
                for (int i = 0; i < list.size(); ++i) {
                    QFileInfo fileInfo = list.at(i);
                    if (!tmp.remove(fileInfo.filePath()))
                        qDebug()<<"[EE] - Can't delete files at: "<<fileInfo.filePath();
                }
            } else {
                if (!tmp.mkdir(tmpDir)){
                    qDebug()<<"[EE] - Can't create temp directory at: "<<tmpDir;
                }
            }

            args << "-o" << tmpDir;
            args << fileName;

            Process exportProcess(args, CoreLib->getSetting("icotool", "wrestool").toString(), QDir::homePath(), tr("Exporting icon from binary file.<br>This can take a while..."), tr("Exporting icon"), FALSE);

            if (exportProcess.exec()==QDialog::Accepted){
            //icotool -x -o ./regedit.png --width=32 --height=32 ./regedit.exe_14_100_0.ico
                args.clear();
                args << "-x";

                QDir ico_dir(tmpDir);
                // Updating file index
                list = ico_dir.entryInfoList();

                //Creating file list for converting
                for (int i = 0; i < list.size(); ++i) {
                    QFileInfo fileInfo = list.at(i);
                    qDebug() << fileInfo.fileName();
                    if (fileInfo.fileName().right(3)=="ico")
                        args << fileInfo.filePath();
                }

                args << "-o" << QString("%1/").arg(tmpDir);

                //Converting ico files to png

//.........这里部分代码省略.........
开发者ID:ercolinux,项目名称:q4wine,代码行数:101,代码来源:iconsettings.cpp


示例3: QString

void TaskManagementMainTab::startNewTaskButtonClicked() {
    CURLcode code;
    long httpCode;
    FILE *tasknml;
    struct httpResponse header;

    auto postdata = QString("csrfmiddlewaretoken=%0&data=<currentTask>%1</currentTask>").arg(taskState::CSRFToken(), state->taskState->taskFile);

    QDir taskDir(QStandardPaths::writableLocation(QStandardPaths::DataLocation) + "/tasks");
    taskDir.mkpath(".");

    state->taskState->taskFile = taskDir.absolutePath() + "/task.tmp.nml";

    tasknml = fopen(state->taskState->taskFile.toUtf8().constData(), "w");
    if (tasknml == nullptr) {
        statusLabel->setText("<font color='red'>Failed to get new task. No write permission in this folder.</font>");
        return;
    }

    auto url = state->taskState->host + "/knossos/newTask/";

    header.length = 0;
    header.content = (char *)calloc(1, header.length + 1);

    setCursor(Qt::WaitCursor);
    httpResponse response;
    response.length = 0;
    response.content = (char *)calloc(1, 10240);
    bool success = taskState::httpFileGET(url.toUtf8().data(), postdata.toUtf8().data(), &response, &header, &httpCode, state->taskState->cookieFile.toUtf8().data(), &code, 5);
    setCursor(Qt::ArrowCursor);
    if(success == false) {
        resetSession(QString("<font color='red'>Could not find session cookie. Please login again.</font><br />%0").arg(response.content));
        return;
    }
    if(code != CURLE_OK) {
        setResponse(QString("<font color='red'>Request failed. Please check your connection.</font><br />%0").arg(response.content));
        taskState::removeCookie();
        free(header.content);
        return;
    }

    if(httpCode == 400) {
        setResponse(QString("<font color='red'>Current task not finished or no new task available.</font><br />%0").arg(response.content));
        QFile(state->taskState->taskFile).remove();
        free(header.content);
        return;
    }
    else if(httpCode == 403) {
        setResponse(QString("<font color='red'>You are not authenticated. Permission denied.</font><br />%0").arg(response.content));
        QFile(state->taskState->taskFile).remove();
        free(header.content);
        return;
    }
    else if(httpCode != 200){
        setResponse(QString("<font color='red'>Error received from server.</font><br />%0").arg(response.content));
        QFile(state->taskState->taskFile).remove();
        free(header.content);
        return;
    }
    fwrite(response.content, 1, response.length, tasknml);
    fclose(tasknml);
    // 200 - success. Retrieve the filename from response header and rename the previously created tmp.nml
    char filename[1024] = {};
    if (taskState::copyInfoFromHeader(filename, &header, "filename")) {
        QFile tmpFile(state->taskState->taskFile);
        tmpFile.rename(filename);
        state->taskState->taskFile = tmpFile.fileName();
    }
    // get task name
    char taskname[1024] = {};
    taskState::copyInfoFromHeader(taskname, &header, "taskname");
    state->taskState->taskName = taskname;
    setTask(state->taskState->taskName);

    // get task category description and task comment
    QByteArray descriptionBuffer(8192, '\0');
    QByteArray commentBuffer(8192, '\0');
    taskState::copyInfoFromHeader(descriptionBuffer.data(), &header, "description");
    taskState::copyInfoFromHeader(commentBuffer.data(), &header, "comment");
    QString description = QByteArray::fromBase64(descriptionBuffer);
    QString comment = QByteArray::fromBase64(commentBuffer);

    QMessageBox prompt;
    prompt.setWindowFlags(Qt::WindowStaysOnTopHint);
    prompt.setIcon(QMessageBox::Information);
    prompt.setWindowTitle(state->taskState->taskName);
    prompt.setText(QString("<p style='width:200px;'><b>Category %1:</b> %2<br><br><b>Task %3:</b> %4</p>")
                   .arg(taskState::getCategory())
                   .arg(description)
                   .arg(taskState::getTask())
                   .arg(comment));
    prompt.addButton("Ok", QMessageBox::ActionRole); // closes prompt by default
    prompt.resize(400, 300);
    prompt.exec();
    emit setDescriptionSignal(description);
    emit setCommentSignal(comment);
    emit loadSkeletonSignal(state->taskState->taskFile);
    setResponse("<font color='green'>Loaded task successfully.</font>");
    free(header.content);
}
开发者ID:dkleissa,项目名称:knossos,代码行数:100,代码来源:taskmanagementmaintab.cpp


示例4: main

int main(int argc, char *argv[])
{
    QCoreApplication app(argc, argv);
    qsrand(time(NULL));
    QStringList args = QCoreApplication::arguments();
    int subcmd = subCommands()->value(args.value(1), Invalid);

    switch (subcmd) {
    case Invalid:
        qCritical("invalid argument");
        return 1;
        break;

    case Help:
        usage();
        break;

    case New:
        // Creates new project
        if (!createNewApplication(args.value(2))) {
            return 1;
        }
        break;

    case ShowDrivers:
        printf("Available database drivers for Qt:\n");
        for (QStringListIterator i(TableSchema::databaseDrivers()); i.hasNext(); ) {
            printf("  %s\n", qPrintable(i.next()));
        }
        break;

    case ShowDriverPath: {
        QString path = QLibraryInfo::location(QLibraryInfo::PluginsPath) + QDir::separator() + "sqldrivers";
        QFileInfo fi(path);
        if (!fi.exists() || !fi.isDir()) {
            qCritical("Error: database driver's directory not found");
            return 1;
        }
        printf("%s\n", qPrintable(fi.canonicalFilePath()));
        break; }

    case ShowTables:
        if (checkIniFile()) {
            QStringList tables = TableSchema::tables();
            if (!tables.isEmpty()) {
                printf("-----------------\nAvailable tables:\n");
                for (QStringListIterator i(tables); i.hasNext(); ) {
                    printf("  %s\n", qPrintable(i.next()));
                }
                putchar('\n');
            }
        } else {
            return 2;
        }
        break;

    case ShowCollections:
        if (checkIniFile()) {
            // MongoDB settings
            QString mongoini = appSettings.value("MongoDbSettingsFile").toString().trimmed();
            QString mnginipath = QLatin1String("config") + QDir::separator() + mongoini;

            if (mongoini.isEmpty() || !QFile(mnginipath).exists()) {
                qCritical("MongoDB settings file not found");
                return 2;
            }

            MongoCommand mongo(mnginipath);
            if (!mongo.open("dev")) {
                return 2;
            }

            QStringList colls = mongo.getCollectionNames();
            printf("-----------------\nExisting collections:\n");
            for (QStringListIterator i(colls); i.hasNext(); ) {
                printf("  %s\n", qPrintable(i.next()));
            }
            putchar('\n');
        }
        break;

    default: {
        if (argc < 3) {
            qCritical("invalid argument");
            return 1;
        }

        if (!checkIniFile()) {
            return 2;
        }

        // Sets codec
        QTextCodec *codec = QTextCodec::codecForName(appSettings.value("InternalEncoding").toByteArray().trimmed());
        codec = (codec) ? codec : QTextCodec::codecForLocale();
        QTextCodec::setCodecForLocale(codec);
#if QT_VERSION < 0x050000
        QTextCodec::setCodecForTr(codec);
        QTextCodec::setCodecForCStrings(codec);
#endif

//.........这里部分代码省略.........
开发者ID:ChowZenki,项目名称:treefrog-framework,代码行数:101,代码来源:main.cpp


示例5: getSelectedLayers

void QgsGeometryCheckerSetupTab::runChecks()
{
  // Get selected layer
  QList<QgsVectorLayer *> layers = getSelectedLayers();
  if ( layers.isEmpty() )
    return;

  if ( ui.radioButtonOutputNew->isChecked() )
  {
    for ( QgsVectorLayer *layer : layers )
    {
      if ( layer->dataProvider()->dataSourceUri().startsWith( ui.lineEditOutputDirectory->text() ) )
      {
        QMessageBox::critical( this, tr( "Invalid Output Directory" ), tr( "The chosen output directory contains one or more input layers." ) );
        return;
      }
    }
  }
  QgsVectorLayer *lineLayerCheckLayer = ui.comboLineLayerIntersection->isEnabled() ? dynamic_cast<QgsVectorLayer *>( QgsProject::instance()->mapLayer( ui.comboLineLayerIntersection->currentData().toString() ) ) : nullptr;
  QgsVectorLayer *followBoundaryCheckLayer = ui.comboBoxFollowBoundaries->isEnabled() ? dynamic_cast<QgsVectorLayer *>( QgsProject::instance()->mapLayer( ui.comboBoxFollowBoundaries->currentData().toString() ) ) : nullptr;
  if ( layers.contains( lineLayerCheckLayer ) || layers.contains( followBoundaryCheckLayer ) )
  {
    QMessageBox::critical( this, tr( "Error" ), tr( "The test layer set contains a layer selected for a topology check." ) );
    return;
  }

  for ( QgsVectorLayer *layer : layers )
  {
    if ( layer->isEditable() )
    {
      QMessageBox::critical( this, tr( "Editable Input Layer" ), tr( "Input layer are not allowed to be in editing mode." ) );
      return;
    }
  }
  bool selectedOnly = ui.checkBoxInputSelectedOnly->isChecked();

  // Set window busy
  setCursor( Qt::WaitCursor );
  mRunButton->setEnabled( false );
  ui.labelStatus->setText( tr( "<b>Preparing output...</b>" ) );
  ui.labelStatus->show();
  QApplication::processEvents( QEventLoop::ExcludeUserInputEvents );

  QList<QgsVectorLayer *> processLayers;
  if ( ui.radioButtonOutputNew->isChecked() )
  {
    // Get output directory and file extension
    QDir outputDir = QDir( ui.lineEditOutputDirectory->text() );
    QString outputDriverName = ui.comboBoxOutputFormat->currentText();
    QgsVectorFileWriter::MetaData metadata;
    if ( !QgsVectorFileWriter::driverMetadata( outputDriverName, metadata ) )
    {
      QMessageBox::critical( this, tr( "Unknown Output Format" ), tr( "The specified output format cannot be recognized." ) );
      mRunButton->setEnabled( true );
      ui.labelStatus->hide();
      unsetCursor();
      return;
    }
    QString outputExtension = metadata.ext;

    // List over input layers, check which existing project layers need to be removed and create output layers
    QString filenamePrefix = ui.lineEditFilenamePrefix->text();
    QSettings().setValue( "/geometry_checker/previous_values/filename_prefix", filenamePrefix );
    QStringList toRemove;
    QStringList createErrors;
    for ( QgsVectorLayer *layer : layers )
    {
      QString outputPath = outputDir.absoluteFilePath( filenamePrefix + layer->name() + "." + outputExtension );

      // Remove existing layer with same uri from project
      for ( QgsVectorLayer *projectLayer : QgsProject::instance()->layers<QgsVectorLayer *>() )
      {
        if ( projectLayer->dataProvider()->dataSourceUri().startsWith( outputPath ) )
        {
          toRemove.append( projectLayer->id() );
        }
      }

      // Create output layer
      QString errMsg;
      QgsVectorFileWriter::WriterError err =  QgsVectorFileWriter::writeAsVectorFormat( layer, outputPath, layer->dataProvider()->encoding(), layer->crs(), outputDriverName, selectedOnly, &errMsg );
      if ( err != QgsVectorFileWriter::NoError )
      {
        createErrors.append( errMsg );
        continue;
      }

      QgsVectorLayer *newlayer = new QgsVectorLayer( outputPath, QFileInfo( outputPath ).completeBaseName(), QStringLiteral( "ogr" ) );
      if ( selectedOnly )
      {
        QgsFeature feature;

        // Get features to select (only selected features were written up to this point)
        QgsFeatureIds selectedFeatures = newlayer->allFeatureIds();

        // Write non-selected feature ids
        QgsFeatureList features;
        QgsFeatureIterator it = layer->getFeatures();
        while ( it.nextFeature( feature ) )
        {
//.........这里部分代码省略.........
开发者ID:giohappy,项目名称:QGIS,代码行数:101,代码来源:qgsgeometrycheckersetuptab.cpp


示例6: i

// 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 || main->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(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(home.absolutePath() + "/" + d.key()).exists() == false) {
            dbaccess->deleteRide(d.key());
#ifdef GC_HAVE_LUCENE
            main->lucene->deleteRide(d.key());
#endif
        }
    }

    unsigned long zoneFingerPrint = zones->getFingerprint() + hrzones->getFingerprint(); // crc 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("Refreshing Ride Statistics...\nStarted");
    QProgressDialog bar(title, tr("Abort"), 0, filenames.count(), main);
    bar.setWindowModality(Qt::WindowModal);
    bar.setMinimumDuration(0);
    bar.show();

    int processed=0;
    QApplication::processEvents(); // get that dialog up!

    // log of progress
    QFile log(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(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;

        // update progress bar
        long elapsedtime = elapsed.elapsed();
        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("Refreshing Ride Statistics...\nElapsed: %1\n%2").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(main, file, errors);

            out << "File open completed: " << name << "\r\n";

            if (ride != NULL) {

                out << "Updating statistics: " << name << "\r\n";
//.........这里部分代码省略.........
开发者ID:BryanF1947,项目名称:GoldenCheetah,代码行数:101,代码来源:MetricAggregator.cpp


示例7: QDialog

IDEGreetingWindow::IDEGreetingWindow(QWidget *parent, IDEProject *project) :
    QDialog(parent)
{
    this->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Minimum);
    this->setWindowTitle("Welcome");
    this->project = project;

    welcomeframe = new QFrame(this, 0);
    welcomeframe->show();
    welcomeframe->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Minimum);

    radiobuttonlist = new QBoxLayout(QBoxLayout::TopToBottom, welcomeframe);
    radiobuttonlist->setSizeConstraint(QLayout::SetMinimumSize);

    greetingtext = new QLabel("Welcome to the blitwizard development environment!\n"
                              "Please specify what you want to do:");
    radiobuttonlist->addWidget((QWidget*)greetingtext);
    greetingtext->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::MinimumExpanding);

    choicenewproject = new QRadioButton("Start new project", 0);
    radiobuttonlist->addWidget((QWidget*)choicenewproject);
    choicenewproject->setChecked(true);

    choiceopenproject = new QRadioButton("Open project from file", 0);
    radiobuttonlist->addWidget((QWidget*)choiceopenproject);

    choicerecentproject = new QRadioButton("Choose from recently opened projects:", 0);
    radiobuttonlist->addWidget((QWidget*)choicerecentproject);

    recentprojectlist = new QListWidget();
    radiobuttonlist->addWidget((QWidget*)recentprojectlist);

    // add recent projects to list:
    std::vector<QString> recentlyOpened = GetApplicationInstance()->settings->getRecentlyOpenedProjects();
    int i = recentlyOpened.size() - 1;
    while (i >= 0) {
        QString f = recentlyOpened[i];
        recentprojectlist->addItem(
                    QString(QFileInfo(QFile(f)).fileName()) + QString(" (") + QString(f) + QString(")"));
        i--;
    }
    if (recentlyOpened.size() == 0) {
        // disable recent project option if no recent projects:
        choicerecentproject->setDisabled(true);
    } else {
        // make recent project the default choice:
        choicerecentproject->setChecked(true);
        choicenewproject->setChecked(false);
        recentprojectlist->setCurrentRow(0);
        QObject::connect(recentprojectlist, SIGNAL(currentRowChanged(int)), this, SLOT(recentProjectChoiceClicked()));
        QObject::connect(recentprojectlist, SIGNAL(clicked(QModelIndex)), this, SLOT(recentProjectChoiceClicked()));
    }

    buttonrowwidget = new QWidget(0, 0);
    radiobuttonlist->addWidget((QWidget*)buttonrowwidget);
    buttonrowwidget->show();
    buttonrowwidget->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);

    buttonrowlayout = new QBoxLayout(QBoxLayout::RightToLeft, buttonrowwidget);

    continuebutton = new QPushButton("Continue", 0);
    buttonrowlayout->addWidget((QWidget*)continuebutton);
    continuebutton->show();
    QObject::connect(continuebutton, SIGNAL(clicked()), this, SLOT(clickedContinue()));

    cancelbutton = new QPushButton("Cancel", 0);
    buttonrowlayout->addWidget((QWidget*)cancelbutton);
    cancelbutton->show();
    QObject::connect(cancelbutton, SIGNAL(clicked()), this, SLOT(clickedCancel()));

    // set proper minimum size:
    this->setMinimumSize(welcomeframe->sizeHint());
}
开发者ID:JonasT,项目名称:Blitwizard-IDE-Unfinished-Unmaintained,代码行数:73,代码来源:idegreetingwindow.cpp


示例8: qDebug

void KIOExec::slotRunApp()
{
    if ( fileList.isEmpty() ) {
        qDebug() << "No files downloaded -> exiting";
        mExited = true;
        QApplication::exit(1);
        return;
    }

    KService service(QStringLiteral("dummy"), command, QString());

    QList<QUrl> list;
    // Store modification times
    QList<FileInfo>::Iterator it = fileList.begin();
    for ( ; it != fileList.end() ; ++it )
    {
        QFileInfo info(QFile::encodeName(it->path));
        it->time = info.lastModified();
        QUrl url = QUrl::fromLocalFile(it->path);
        list << url;
    }

    KIO::DesktopExecParser execParser(service, list);
    QStringList params = execParser.resultingArguments();

    qDebug() << "EXEC " << params.join(QStringLiteral(" "));

#if (QT_VERSION >= QT_VERSION_CHECK(5, 4, 0))
    // propagate the startup identification to the started process
    KStartupInfoId id;
    QByteArray startupId;
#if HAVE_X11
    if (QX11Info::isPlatformX11()) {
        startupId = QX11Info::nextStartupId();
    }
#endif
    id.initId(startupId);
    id.setupStartupEnv();
#endif

    QString exe( params.takeFirst() );
    const int exit_code = QProcess::execute( exe, params );

#if (QT_VERSION >= QT_VERSION_CHECK(5, 4, 0))
    KStartupInfo::resetStartupEnv();
#endif

    qDebug() << "EXEC done";

    // Test whether one of the files changed
    for(it = fileList.begin(); it != fileList.end(); ++it )
    {
        QString src = it->path;
        const QUrl dest = it->url;
        QFileInfo info(src);
        if ( info.exists() && (it->time != info.lastModified()) )
        {
            if ( mTempFiles )
            {
                if ( KMessageBox::questionYesNo( 0L,
                                                 i18n( "The supposedly temporary file\n%1\nhas been modified.\nDo you still want to delete it?", dest.toDisplayString(QUrl::PreferLocalFile)),
                                                 i18n( "File Changed" ), KStandardGuiItem::del(), KGuiItem(i18n("Do Not Delete")) ) != KMessageBox::Yes )
                    continue; // don't delete the temp file
            }
            else if ( ! dest.isLocalFile() )  // no upload when it's already a local file
            {
                if ( KMessageBox::questionYesNo( 0L,
                                                 i18n( "The file\n%1\nhas been modified.\nDo you want to upload the changes?" , dest.toDisplayString()),
                                                 i18n( "File Changed" ), KGuiItem(i18n("Upload")), KGuiItem(i18n("Do Not Upload")) ) == KMessageBox::Yes )
                {
                    qDebug() << "src='" << src << "'  dest='" << dest << "'";
                    // Do it the synchronous way.
                    KIO::CopyJob* job = KIO::copy(QUrl::fromLocalFile(src), dest);
                    if ( !job->exec() )
                    {
                        KMessageBox::error( 0L, job->errorText() );
                        continue; // don't delete the temp file
                    }
                }
            }
        }

        if ((!dest.isLocalFile() || mTempFiles) && exit_code == 0) {
            // Wait for a reasonable time so that even if the application forks on startup (like OOo or amarok)
            // it will have time to start up and read the file before it gets deleted. #130709.
            qDebug() << "sleeping...";
            QThread::currentThread()->sleep(180); // 3 mn
            qDebug() << "about to delete " << src;
            QFile( QFile::encodeName(src) ).remove();
        }
    }

    mExited = true;
    QApplication::exit(exit_code);
}
开发者ID:emmanuel099,项目名称:kio,代码行数:95,代码来源:main.cpp


示例9: return

bool PathHelper::isFileExistsAndItsReallyAFile(QString filePath)
{
    return (!filePath.isEmpty() && QFile(filePath).exists() && !QDir(filePath).exists());
}
开发者ID:Bitfall,项目名称:AppWhirr-SamplesAndPrototypes,代码行数:4,代码来源:pathhelper.cpp


示例10: dir

void Settings::loadPersonal(Profile* profile)
{
    QMutexLocker locker{&bigLock};

    QDir dir(getSettingsDirPath());
    QString filePath = dir.filePath(globalSettingsFile);

    // load from a profile specific friend data list if possible
    QString tmp = dir.filePath(profile->getName() + ".ini");
    if (QFile(tmp).exists()) // otherwise, filePath remains the global file
        filePath = tmp;

    qDebug()<<"Loading personal settings from"<<filePath;

    SettingsSerializer ps(filePath, profile->getPassword());
    ps.load();
    friendLst.clear();

    ps.beginGroup("Privacy");
        typingNotification = ps.value("typingNotification", true).toBool();
        enableLogging = ps.value("enableLogging", true).toBool();
    ps.endGroup();

    ps.beginGroup("Friends");
        int size = ps.beginReadArray("Friend");
        friendLst.reserve(size);
        for (int i = 0; i < size; i ++)
        {
            ps.setArrayIndex(i);
            friendProp fp;
            fp.addr = ps.value("addr").toString();
            fp.alias = ps.value("alias").toString();
            fp.note = ps.value("note").toString();
            fp.autoAcceptDir = ps.value("autoAcceptDir").toString();
            fp.circleID = ps.value("circle", -1).toInt();

            if (getEnableLogging())
                fp.activity = ps.value("activity", QDate()).toDate();

            friendLst[ToxId(fp.addr).publicKey] = fp;
        }
        ps.endArray();
    ps.endGroup();

    ps.beginGroup("General");
        compactLayout = ps.value("compactLayout", true).toBool();
    ps.endGroup();

    ps.beginGroup("Circles");
        size = ps.beginReadArray("Circle");
        circleLst.clear();
        circleLst.reserve(size);
        for (int i = 0; i < size; i ++)
        {
            ps.setArrayIndex(i);
            circleProp cp;
            cp.name = ps.value("name").toString();
            cp.expanded = ps.value("expanded", true).toBool();
            circleLst.push_back(cp);
        }
        ps.endArray();
    ps.endGroup();
}
开发者ID:Doom032,项目名称:qTox,代码行数:63,代码来源:settings.cpp


示例11: createSettingsDir

void Settings::loadGlobal()
{
    QMutexLocker locker{&bigLock};

    if (loaded)
        return;

    createSettingsDir();

    if (QFile(globalSettingsFile).exists())
    {
        QSettings ps(globalSettingsFile, QSettings::IniFormat);
        ps.setIniCodec("UTF-8");
        ps.beginGroup("General");
            makeToxPortable = ps.value("makeToxPortable", false).toBool();
        ps.endGroup();
    }
    else
    {
        makeToxPortable = false;
    }

    QDir dir(getSettingsDirPath());
    QString filePath = dir.filePath(globalSettingsFile);

    // If no settings file exist -- use the default one
    if (!QFile(filePath).exists())
    {
        qDebug() << "No settings file found, using defaults";
        filePath = ":/conf/" + globalSettingsFile;
    }

    qDebug() << "Loading settings from " + filePath;

    QSettings s(filePath, QSettings::IniFormat);
    s.setIniCodec("UTF-8");
    s.beginGroup("Login");
        autoLogin = s.value("autoLogin", false).toBool();
    s.endGroup();

    s.beginGroup("DHT Server");
        if (s.value("useCustomList").toBool())
        {
            useCustomDhtList = true;
            qDebug() << "Using custom bootstrap nodes list";
            int serverListSize = s.beginReadArray("dhtServerList");
            for (int i = 0; i < serverListSize; i ++)
            {
                s.setArrayIndex(i);
                DhtServer server;
                server.name = s.value("name").toString();
                server.userId = s.value("userId").toString();
                server.address = s.value("address").toString();
                server.port = s.value("port").toInt();
                dhtServerList << server;
            }
            s.endArray();
        }
        else
        {
            useCustomDhtList=false;
        }
    s.endGroup();

    s.beginGroup("General");
        enableIPv6 = s.value("enableIPv6", true).toBool();
        translation = s.value("translation", "en").toString();
        showSystemTray = s.value("showSystemTray", SHOW_SYSTEM_TRAY_DEFAULT).toBool();
        makeToxPortable = s.value("makeToxPortable", false).toBool();
        autostartInTray = s.value("autostartInTray", false).toBool();
        closeToTray = s.value("closeToTray", false).toBool();
        forceTCP = s.value("forceTCP", false).toBool();
        setProxyType(s.value("proxyType", static_cast<int>(ProxyType::ptNone)).toInt());
        proxyAddr = s.value("proxyAddr", "").toString();
        proxyPort = s.value("proxyPort", 0).toInt();
        if (currentProfile.isEmpty())
        {
            currentProfile = s.value("currentProfile", "").toString();
            currentProfileId = makeProfileId(currentProfile);
        }
        autoAwayTime = s.value("autoAwayTime", 10).toInt();
        checkUpdates = s.value("checkUpdates", true).toBool();
        showWindow = s.value("showWindow", true).toBool();
        showInFront = s.value("showInFront", false).toBool();
        notifySound = s.value("notifySound", true).toBool();
        groupAlwaysNotify = s.value("groupAlwaysNotify", false).toBool();
        fauxOfflineMessaging = s.value("fauxOfflineMessaging", true).toBool();
        autoSaveEnabled = s.value("autoSaveEnabled", false).toBool();
        globalAutoAcceptDir = s.value("globalAutoAcceptDir",
                                      QStandardPaths::locate(QStandardPaths::HomeLocation, QString(), QStandardPaths::LocateDirectory)
                                      ).toString();
        separateWindow = s.value("separateWindow", false).toBool();
        dontGroupWindows = s.value("dontGroupWindows", true).toBool();
        groupchatPosition = s.value("groupchatPosition", true).toBool();
        markdownPreference = static_cast<MarkdownType>(s.value("markdownPreference", 1).toInt());
    s.endGroup();

    s.beginGroup("Advanced");
        int sType = s.value("dbSyncType", static_cast<int>(Db::syncType::stFull)).toInt();
        setDbSyncType(sType);
//.........这里部分代码省略.........
开发者ID:Doom032,项目名称:qTox,代码行数:101,代码来源:settings.cpp


示例12: windowGeometry

void MainWindow::loadConfig()
{
    // Default geometry values
    QRect windowGeometry(50, 50, 700, 400);

    // Load and parse config file if exists
    bool configExists = QFile(this->userFolder + CONFIG_FILE).exists();
    if (configExists)
    {
        QFile file(this->userFolder + CONFIG_FILE);
        if (file.open(QFile::ReadOnly | QIODevice::Text))
        {
            QTextStream in(&file);
            QString data("");
            while (!in.atEnd())
            {
                QString line(in.readLine().trimmed());

                if (line.startsWith("#") || line.isEmpty())
                    continue;

                QStringList parts = line.split("=");
                if (parts.count() != 2)
                    continue;
                QString key = parts.at(0).trimmed().toLower();
                QString value = parts.at(1).trimmed();

                if (key == "serverip")
                    this->serverIp.setAddress(value);
                if (key == "serverport")
                    this->serverPort = value.toInt();
                if (key == "timeoutvalue")
                    this->timeoutValue = value.toInt();
                if (key == "timeoutenabled")
                    this->timeoutEnabled = (value == "1") ? true : false;
                if (key == "windowx")
                    windowGeometry.setX(value.toInt());
                if (key == "windowy")
                    windowGeometry.setY(value.toInt());
                if (key == "windoww")
                    windowGeometry.setWidth(value.toInt());
                if (key == "windowh")
                    windowGeometry.setHeight(value.toInt());
                if (key == "tab1caption")
                    this->tabCaptions[0] = value;
                if (key == "tab2caption")
                    this->tabCaptions[1] = value;
                if (key == "tab3caption")
                    this->tabCaptions[2] = value;
                if (key == "tab4caption")
                    this->tabCaptions[3] = value;
                if (key == "tab5caption")
                    this->tabCaptions[4] = value;
                if (key == "controlsvisible")
                    this->controlsVisible = (value == "1") ? true : false;
                if (key == "layout")
                    this->layoutType = (LayoutType) value.toInt();
            }
            file.close();
        }
    }

    // Load and parse styles file if exists
    bool stylesExists = QFile(this->userFolder + STYLES_FILE).exists();
    if (stylesExists)
    {
        QFile file(this->userFolder + STYLES_FILE);
        if (file.open(QFile::ReadOnly | QIODevice::Text))
        {
            QTextStream in(&file);
            QString data("");
            while (!in.atEnd())
            {
                QString line(in.readLine().trimmed());

                if (line.startsWith("#") || line.isEmpty())
                    continue;

                QStringList parts = line.split("=");
                if (parts.count() != 2)
                    continue;
                QString key = parts.at(0).trimmed().toLower();
                QString value = parts.at(1).trimmed();

                this->styles[key] = value;
            }
            file.close();
        }
    }

    // Apply geometry values
    this->setGeometry(windowGeometry);
}
开发者ID:koas,项目名称:maurina,代码行数:93,代码来源:MainWindow.cpp


示例13: QFile

bool SmileyPack::isValid(const QString& filename)
{
    return QFile(filename).exists();
}
开发者ID:apprb,项目名称:qTox,代码行数:4,代码来源:smileypack.cpp


示例14: QFile

FetchSqlite::~FetchSqlite()
{
    if(m_db.isOpen()) m_db.close();
    QFile(m_databaseFile).remove();
}
开发者ID:KDE,项目名称:plasma-workspace,代码行数:5,代码来源:fetchsqlite.cpp


示例15: Q_ASSERT

该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C++ QFileInfo函数代码示例发布时间:2022-05-30
下一篇:
C++ QF_INT_DISABLE函数代码示例发布时间:2022-05-30
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap