当前位置: 首页>>代码示例>>C++>>正文


C++ QFile::readAll方法代码示例

本文整理汇总了C++中QFile::readAll方法的典型用法代码示例。如果您正苦于以下问题:C++ QFile::readAll方法的具体用法?C++ QFile::readAll怎么用?C++ QFile::readAll使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在QFile的用法示例。


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

示例1: main

int main(int argc, char** argv)
{
    QTextCodec::setCodecForLocale(QTextCodec::codecForName("latin1"));
    AppliArgs args(QStringList() << "~help,h" << "~version,v" << "output=1,o");
    QTextStream out(stdout), err(stderr);
    unsigned long int length;
    struct jbg_dec_state sd;
    unsigned char *buffer;
    QString hw("%1 %2\n");
    QByteArray data;
    bool argsErr;
    QFile input;

    // Parse arguments
    argsErr = !args.parse(argc, argv, 1);
    if (argsErr || args.isOptionSet("help")) {
        args.printErrors(err);

        out << QString(_("Usage: %1 [options] <JBIG file>")).arg(args.
            applicationName()) << endl;
        out << _("Available options:") << endl;
        out << _("  --help, -h                Print this help message") << endl;
        out << _("  --output, -o              Select the output file") << endl;
        out << _("  --version, -v             Print the version information") <<
            endl;
        return argsErr ? 1 : 0;
    } else if (args.isOptionSet("version")) {
        out << _("(C) jbgtopbm, 2007 by Aurélien Croc") << endl;
        out << _("This project is under the GNU General Public Licence "
            "version 2") << endl;
        out << _("More information => http://splix.ap2c.org") << endl << endl;
        return 0;
    }


    // Open the input and the output file
    input.setFileName(args.parameter(0));
    if (!input.open(QIODevice::ReadOnly)) {
        err << _("Error: cannot open file ") << args.parameter(0) << endl;
        return -1;
    }
    data = input.readAll();
    buffer = (unsigned char *)data.data();
    length = data.length();
    if (args.isOptionSet("output"))
        output.setFileName(args.optionArg("output", 0));
    else
        output.setFileName("/dev/stdout");
    if (!output.open(QIODevice::WriteOnly)) {
        err << _("Error: cannot open file ") << output.fileName() << endl;
        return -1;
    }


    // Decompress the image
    jbg_dec_init(&sd);
    while (length) {
        unsigned long size;
        int res;

        size = *(unsigned long*)buffer;
        printf("Taille=%lu\n", size);
        buffer += sizeof(size);
        length -= sizeof(size);
        res = jbg_dec_in(&sd, buffer, size, NULL);
        if (res == JBG_EOK) {
            out << _("Processed.") << endl;
            break;
        } else if (res != JBG_EAGAIN) {
            err << _("JBG not ok ") << res << endl;
            break;
        }
        length -= size;
        buffer += size;
    }

    // Store the image
    output.write("P4\n");
    output.write("# Image created by jbgtopbm, (C) 2007 by Aurélien Croc "
        "(AP²C)\n");
    hw = hw.arg(jbg_dec_getwidth(&sd)).arg(jbg_dec_getheight(&sd));
    output.write(hw.toAscii());
    output.write((const char *)jbg_dec_getimage(&sd, 0), jbg_dec_getsize(&sd));
    output.close();

    return 0;
}
开发者ID:jianglei12138,项目名称:splix,代码行数:87,代码来源:jbgtopbm.cpp

示例2: SetBaseFileDoc

void FoxGroundDocument::SetBaseFileDoc(const QString file) {

    QFileInfo localfile(file);
    if (!localfile.exists()) {
        CurrentRunDoc = UNKNOW;
        return;
    }
    document_file = file;
    //// try on pole...
    bool poleisrun = false;
    POLE::Storage storage(file.toLocal8Bit());
    if (storage.open()) {
        QBuffer basestore;
        if (Conversion::readStreamPole(storage, "/SummaryInformation", basestore)) {
            LEInputStream *sis_baseSummaryInformation = new LEInputStream(&basestore);
            poleisrun = true;
            CurrentRunDoc = OFFICEMSO;
            document_name = "DOC";
        }
    }
    QByteArray x;
    QFile *f = new QFile(file);
    if (f->open(QIODevice::ReadOnly)) {
        x = f->readAll();
    }
    f->close();
    const QByteArray data = x;
    QDomDocument document;
    QString c;
    int d, o;
    bool xmlbased = false;
    if (document.setContent(data, true, &c)) {
        /// not xml based...
        xmlbased = true;
    }
    const QByteArray rtfsearch = x.mid(0, 5).simplified();
    /// qDebug() << "rtfsearch :" << rtfsearch;
    //// no office family .. doc
    if (!poleisrun) {
        if (xmlbased && data.indexOf("encoding=") != -1) {
            if (data.indexOf("DOCTYPE html") > 0) {
                CurrentRunDoc = HTML;
                document_name = "HTML";
            } else {
                document_name = "XML";
                CurrentRunDoc = XML;
            }
        } else if (rtfsearch == "{\\rtf") {
            CurrentRunDoc = RTF;
            document_name = "RTF";
        } else if (data.mid(0, 4) == "%PDF") {
            if (bin_pdftohtml.size() > 3) {
                CurrentRunDoc = PDF;
                document_name = "PDF";
            } else {
                CurrentRunDoc = UNKNOW;
            }
        } else if (data.mid(0, 2) == "PK") {
            KZip::Stream *unzip = new KZip::Stream(file);
            if (unzip->canread()) {
                unzipfileliste = unzip->filelist();
                corefile = unzip->listData();
                if (docitem("word/document.xml").size() > 20) {
                    CurrentRunDoc = DOCX;
                    document_name = "DOCX";
                } else if (docitem("content.xml").size() > 20) {
                    CurrentRunDoc = ODT;
                    document_name = "ODT";
                } else {
                    CurrentRunDoc = UNKNOW;
                }
            }
            unzip->~Stream();
            unzip = NULL;
        } else {
            CurrentRunDoc = UNKNOW;
        }
    }

    if (CurrentRunDoc == UNKNOW) {
        document_name = "NULL";
    }
}
开发者ID:FranciscoJavierPRamos,项目名称:wv2qt,代码行数:83,代码来源:fox_base.cpp

示例3: create

/************************************************************
** Member Function
**
** Name: create
** Parameter: xmlUI - XML UI's file
** Returned Value: bool - Successed return true, failed return
**													  false
** Intro: Create a widget by xml string.
************************************************************/
bool FFactory::create(QFile xmlUI) {
	QString xmlText = xmlUI.readAll();
	return create(xmlText);
}
开发者ID:LeLe570929726,项目名称:HerplasQt,代码行数:13,代码来源:FFactory.cpp

示例4: run

void UploadAssetTask::run() {
    auto data = _receivedMessage->getMessage();
    
    QBuffer buffer { &data };
    buffer.open(QIODevice::ReadOnly);
    
    MessageID messageID;
    buffer.read(reinterpret_cast<char*>(&messageID), sizeof(messageID));
    
    uint64_t fileSize;
    buffer.read(reinterpret_cast<char*>(&fileSize), sizeof(fileSize));
    
    qDebug() << "UploadAssetTask reading a file of " << fileSize << "bytes from"
        << uuidStringWithoutCurlyBraces(_senderNode->getUUID());
    
    auto replyPacket = NLPacket::create(PacketType::AssetUploadReply);
    replyPacket->writePrimitive(messageID);
    
    if (fileSize > MAX_UPLOAD_SIZE) {
        replyPacket->writePrimitive(AssetServerError::AssetTooLarge);
    } else {
        QByteArray fileData = buffer.read(fileSize);
        
        auto hash = hashData(fileData);
        auto hexHash = hash.toHex();
        
        qDebug() << "Hash for uploaded file from" << uuidStringWithoutCurlyBraces(_senderNode->getUUID())
            << "is: (" << hexHash << ") ";
        
        QFile file { _resourcesDir.filePath(QString(hexHash)) };

        bool existingCorrectFile = false;
        
        if (file.exists()) {
            // check if the local file has the correct contents, otherwise we overwrite
            if (file.open(QIODevice::ReadOnly) && hashData(file.readAll()) == hash) {
                qDebug() << "Not overwriting existing verified file: " << hexHash;

                existingCorrectFile = true;

                replyPacket->writePrimitive(AssetServerError::NoError);
                replyPacket->write(hash);
            } else {
                qDebug() << "Overwriting an existing file whose contents did not match the expected hash: " << hexHash;
                file.close();
            }
        }

        if (!existingCorrectFile) {
            if (file.open(QIODevice::WriteOnly) && file.write(fileData) == qint64(fileSize)) {
                qDebug() << "Wrote file" << hexHash << "to disk. Upload complete";
                file.close();

                replyPacket->writePrimitive(AssetServerError::NoError);
                replyPacket->write(hash);
            } else {
                qWarning() << "Failed to upload or write to file" << hexHash << " - upload failed.";

                // upload has failed - remove the file and return an error
                auto removed = file.remove();

                if (!removed) {
                    qWarning() << "Removal of failed upload file" << hexHash << "failed.";
                }
                
                replyPacket->writePrimitive(AssetServerError::FileOperationFailed);
            }
        }


    }
    
    auto nodeList = DependencyManager::get<NodeList>();
    nodeList->sendPacket(std::move(replyPacket), *_senderNode);
}
开发者ID:BingShearer,项目名称:hifi,代码行数:75,代码来源:UploadAssetTask.cpp

示例5: nextSPICE

// ---------------------------------------------------
// Converts a spice netlist into Qucs format and outputs it.
void SimMessage::nextSPICE()
{ 
  QString Line;
  for(;;) {  // search for next SPICE component
    Line = *(Collect.begin());
    Collect.remove(Collect.begin());
    if(Line == "*") {  // worked on all components ?
      startSimulator(); // <<<<<================== go on ===
      return;
    }
#warning SPICE section below not being covered?
    qDebug() << "goin thru SPICE branch on simmmessage.cpp";
    if(Line.left(5) == "SPICE") {
      if(Line.at(5) != 'o') insertSim = true;
      else insertSim = false;
      break;
    }
    Collect.append(Line);
  }


  QString FileName = Line.section('"', 1,1);
  Line = Line.section('"', 2);  // port nodes
  if(Line.isEmpty())  makeSubcircuit = false;
  else  makeSubcircuit = true;

  QString prog;
  QStringList com;
  prog = QucsSettings.BinDir + "qucsconv";
  if(makeSubcircuit)
    com << "-g" << "_ref";
  com << "-if" << "spice" << "-of" << "qucs";

  QFile SpiceFile;
  if(FileName.find(QDir::separator()) < 0)  // add path ?
    SpiceFile.setName(QucsWorkDir.path() + QDir::separator() + FileName);
  else
    SpiceFile.setName(FileName);
  if(!SpiceFile.open(QIODevice::ReadOnly)) {
    ErrText->insert(tr("ERROR: Cannot open SPICE file \"%1\".").arg(FileName));
    FinishSimulation(-1);
    return;
  }

  if(makeSubcircuit) {
    Stream << "\n.Def:" << properName(FileName) << " ";
  
    Line.replace(',', ' ');
    Stream << Line;
    if(!Line.isEmpty()) Stream << " _ref";
  }
  Stream << "\n";

  ProgressText = "";
  
  qDebug() << "start QucsConv" << prog << com.join(" ");
  SimProcess.start(prog, com);
  
  if(!SimProcess.Running) {
    ErrText->insert(tr("ERROR: Cannot start QucsConv!"));
    FinishSimulation(-1);
    return;
  }

  QByteArray SpiceContent = SpiceFile.readAll();
  SpiceFile.close();
  QString command(SpiceContent); //to convert byte array to string
  SimProcess.setStandardInputFile(command);  //? FIXME works?
  qDebug() << command;
  connect(&SimProcess, SIGNAL(wroteToStdin()), SLOT(slotCloseStdin()));
}
开发者ID:bastien-roucaries,项目名称:qucsrework,代码行数:73,代码来源:simmessage.cpp

示例6: parseSingleConfigFile

void KConfigINIBackEnd::parseSingleConfigFile(QFile &rFile, KEntryMap *pWriteBackMap, bool bGlobal, bool bDefault)
{
    const char *s;   // May get clobbered by sigsetjump, but we don't use them afterwards.
    const char *eof; // May get clobbered by sigsetjump, but we don't use them afterwards.
    QByteArray data;

    if(!rFile.isOpen()) // come back, if you have real work for us ;->
        return;

    // using kdDebug() here leads to an infinite loop
    // remove this for the release, aleXXX
    // qWarning("Parsing %s, global = %s default = %s",
    //           rFile.name().latin1(), bGlobal ? "true" : "false", bDefault ? "true" : "false");

    QCString aCurrentGroup("<default>");

    unsigned int ll = localeString.length();

#ifdef HAVE_MMAP
    static volatile const char *map;
    map = (const char *)mmap(0, rFile.size(), PROT_READ, MAP_PRIVATE, rFile.handle(), 0);

    if(map != MAP_FAILED)
    {
        s = (const char *)map;
        eof = s + rFile.size();

#ifdef SIGBUS
        struct sigaction act;
        act.sa_handler = mmap_sigbus_handler;
        sigemptyset(&act.sa_mask);
#ifdef SA_ONESHOT
        act.sa_flags = SA_ONESHOT;
#else
        act.sa_flags = SA_RESETHAND;
#endif
        sigaction(SIGBUS, &act, &mmap_old_sigact);

        if(sigsetjmp(mmap_jmpbuf, 1))
        {
            qWarning("SIGBUS while reading %s", rFile.name().latin1());
            munmap((char *)map, rFile.size());
            sigaction(SIGBUS, &mmap_old_sigact, 0);
            return;
        }
#endif
    }
    else
#endif
    {
        rFile.at(0);
        data = rFile.readAll();
        s = data.data();
        eof = s + data.size();
    }

    bool fileOptionImmutable = false;
    bool groupOptionImmutable = false;
    bool groupSkip = false;

    int line = 0;
    for(; s < eof; s++)
    {
        line++;

        while((s < eof) && isspace(*s) && (*s != '\n'))
            s++; // skip leading whitespace, shouldn't happen too often

        // skip empty lines, lines starting with #
        if((s < eof) && ((*s == '\n') || (*s == '#')))
        {
        sktoeol: // skip till end-of-line
            while((s < eof) && (*s != '\n'))
                s++;
            continue; // Empty or comment or no keyword
        }
        const char *startLine = s;

        if(*s == '[') // group
        {
            // In a group [[ and ]] have a special meaning
            while((s < eof) && (*s != '\n'))
            {
                if(*s == ']')
                {
                    if((s + 1 < eof) && (*(s + 1) == ']'))
                        s++; // Skip "]]"
                    else
                        break;
                }

                s++; // Search till end of group
            }
            const char *e = s;
            while((s < eof) && (*s != '\n'))
                s++; // Search till end of line / end of file
            if((e >= eof) || (*e != ']'))
            {
                fprintf(stderr, "Invalid group header at %s:%d\n", rFile.name().latin1(), line);
                continue;
//.........这里部分代码省略.........
开发者ID:serghei,项目名称:kde3-kdelibs,代码行数:101,代码来源:kconfigbackend.cpp

示例7: loadEntityServerFile

void ATPAssetMigrator::loadEntityServerFile() {
    auto filename = QFileDialog::getOpenFileName(_dialogParent, "Select an entity-server content file to migrate",
                                                 QString(), QString("Entity-Server Content (*.gz)"));
    
    if (!filename.isEmpty()) {
        qCDebug(asset_migrator) << "Selected filename for ATP asset migration: " << filename;
        
        static const QString MIGRATION_CONFIRMATION_TEXT {
            "The ATP Asset Migration process will scan the selected entity-server file, upload discovered resources to the"\
            " current asset-server and then save a new entity-server file with the ATP URLs.\n\nAre you ready to"\
            " continue?\n\nMake sure you are connected to the right domain."
        };
        
        auto button = QMessageBox::question(_dialogParent, MESSAGE_BOX_TITLE, MIGRATION_CONFIRMATION_TEXT,
                                            QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes);
        
        if (button == QMessageBox::No) {
            return;
        }
        
        // try to open the file at the given filename
        QFile modelsFile { filename };
        
        if (modelsFile.open(QIODevice::ReadOnly)) {
            QByteArray compressedJsonData = modelsFile.readAll();
            QByteArray jsonData;
            
            if (!gunzip(compressedJsonData, jsonData)) {
                QMessageBox::warning(_dialogParent, "Error", "The file at" + filename + "was not in gzip format.");
            }
            
            QJsonDocument modelsJSON = QJsonDocument::fromJson(jsonData);
            _entitiesArray = modelsJSON.object()["Entities"].toArray();
            
            for (auto jsonValue : _entitiesArray) {
                QJsonObject entityObject = jsonValue.toObject();
                QString modelURLString = entityObject.value(MODEL_URL_KEY).toString();
                
                if (!modelURLString.isEmpty()) {
                    QUrl modelURL = QUrl(modelURLString);
                    
                    if (!_ignoredUrls.contains(modelURL)
                        && (modelURL.scheme() == URL_SCHEME_HTTP || modelURL.scheme() == URL_SCHEME_HTTPS
                            || modelURL.scheme() == URL_SCHEME_FILE || modelURL.scheme() == URL_SCHEME_FTP)) {
                        
                        if (_pendingReplacements.contains(modelURL)) {
                            // we already have a request out for this asset, just store the QJsonValueRef
                            // so we can do the hash replacement when the request comes back
                            _pendingReplacements.insert(modelURL, jsonValue);
                        } else if (_uploadedAssets.contains(modelURL)) {
                            // we already have a hash for this asset
                            // so just do the replacement immediately
                            entityObject[MODEL_URL_KEY] = _uploadedAssets.value(modelURL).toString();
                            jsonValue = entityObject;
                        } else if (wantsToMigrateResource(modelURL)) {
                            auto request = ResourceManager::createResourceRequest(this, modelURL);
                            
                            if (request) {
                                qCDebug(asset_migrator) << "Requesting" << modelURL << "for ATP asset migration";
                                
                                // add this combination of QUrl and QJsonValueRef to our multi hash so we can change the URL
                                // to an ATP one once ready
                                _pendingReplacements.insert(modelURL, jsonValue);
                                
                                connect(request, &ResourceRequest::finished, this, [=]() {
                                    if (request->getResult() == ResourceRequest::Success) {
                                        migrateResource(request);
                                    } else {
                                        QMessageBox::warning(_dialogParent, "Error",
                                                             QString("Could not retrieve asset at %1").arg(modelURL.toString()));
                                    }
                                    request->deleteLater();
                                });
                                
                                request->send();
                            } else {
                                QMessageBox::warning(_dialogParent, "Error",
                                                     QString("Could not create request for asset at %1").arg(modelURL.toString()));
                            }
                            
                        } else {
                            _ignoredUrls.insert(modelURL);
                        }
                    }
                }
            }
            
            _doneReading = true;
            
        } else {
            QMessageBox::warning(_dialogParent, "Error",
                                 "There was a problem loading that entity-server file for ATP asset migration. Please try again");
        }
    }
}
开发者ID:Giugiogia,项目名称:hifi,代码行数:95,代码来源:ATPAssetMigrator.cpp

示例8: readSuffixFilter

void LocalApp::readSuffixFilter(){
    QFile *suffixFilterFile = 0;
    if ( appName == "home")
        suffixFilterFile = new QFile (home+"/"+QString("home.suffixfilter"));
    else
        suffixFilterFile = new QFile (home+"/"+ appName + "/"+ appName + QString(".suffixfilter"));
    ERR<<"INFO: LocalApp::readSuffixFilter(): "<<suffixFilterFile->fileName()<<endl;
#ifndef USE_QT5
    if ( ! suffixFilterFile->open(QIODevice::ReadOnly) ){
#else
    if ( ! suffixFilterFile->open(QFile::ReadOnly) ){
#endif
        ERR<<"WARN: LocalApp::readSuffixFilter(): Unable to read : "<<suffixFilterFile->fileName()<<endl;
        suffixFilterFile->close();

    }else {
        suffixFilter += suffixFilterFile->readAll();
        suffixFilterFile->close();
    }

    //TODO: convert suffix filter to map of string
    ERR<<"DBUG: LocalApp::readSuffixFilter(): "<<suffixFilter<<endl;
    delete suffixFilterFile;
}

void LocalApp::readLibraryLoadConfig(){
    QFile *llConfigFile = 0;
    if ( appName == "home")
        llConfigFile = new QFile (home+"/"+QString("home.cfg"));
    else
        llConfigFile = new QFile (home+"/"+ appName + "/"+ appName + QString(".cfg"));
#ifndef USE_QT5
    if ( ! llConfigFile->open(QIODevice::ReadOnly) ){
#else
    if ( ! llConfigFile->open(QFile::ReadOnly) ){
#endif
        ERR<<"DBUG: LocalApp::readLibraryLoadConfig(): Unable to open file :"<<llConfigFile->fileName()<<endl;
    } else {
        QByteArray libConfig;
        while ( (libConfig = llConfigFile->readLine() ).length() > 0 ){
            /*
             * Read the config file
             * <scriptname>:<libraryname>
             */
            QString line(libConfig);
            if( line.split(":").length() > 1) {
                QString script = line.split(":")[0];
                QString soFile = line.split(":")[1];
#ifndef WINDOWS
                soFile.replace(QString("\n"), QString(""));
                soFile += QString(".so");
                //soFile.remove(soFile.length()-1,1);
#else
                soFile.replace(QString("\r\n"), QString(""));
                soFile += QString(".dll");
                //soFile.remove(soFile.length()-2,2);
#endif
                if( appName == "home"){
                    QLibrary *lib = new QLibrary( home + "/" + soFile );
                    lib->setLoadHints(QLibrary::ResolveAllSymbolsHint);
                    lib->load();
                    ERR<<"ERRR: LocalApp::readLibraryLoadConfig(): "<< script<<" -> "<<lib->fileName()<<": Loaded ? "<<lib->isLoaded()<<endl;
                    mapScriptToSo[script] = lib;

                } else {
                    QLibrary *lib = new QLibrary( home + "/" + appName + "/" + soFile, this );
                    lib->setLoadHints(QLibrary::ResolveAllSymbolsHint);
                    lib->load();
                    ERR<<"ERRR: LocalApp::readLibraryLoadConfig(): "<<script<<" -> "<<lib->fileName()<<": Loaded ? "<<lib->isLoaded()<<endl;
                    mapScriptToSo[script] = lib;
                }
            }
        }
    }

    delete llConfigFile;
}


QString LocalApp::readAppName( QUrl url ){
    QString app("");
#ifndef USE_QT5
    ERR<<"INFO: LocalApp::readAppName(): Encoded Path: "<<url.encodedPath()<<endl;
    //QStringList
    app = url.encodedPath().split('/')[0];
    //app = list[0];
    if ( app.contains(".py")){
       app = "home";
    }
    ERR<<"INFO: LocalApp::readAppName(): App: "<<app<<endl;
#else
    ERR<<"INFO: LocalApp::readAppName(): Path: "<<url.path()<<endl;
    app = url.path().split('/')[0];
    if ( app.contains(".py") || app.contains(".")){
        app = "home";
    }
    ERR<<"INFO: LocalApp::readAppName(): App: "<<app<<endl;
    ERR<<"INFO: LocalApp::readAppName(): Path: "<<url.path()<<endl;
#endif
    return app;
//.........这里部分代码省略.........
开发者ID:r9al,项目名称:QuikApps,代码行数:101,代码来源:localapp.cpp

示例9: main


//.........这里部分代码省略.........
            break; // all other params not matter
        }
        if (value == _S("--execute") && i+1 < args.count())
        {
            executeModule = args.at(++i);
            executeParams = args.at(++i);
            continue;
        }
        // если не параметров - значит название базы
        mainBase = value;
    }


    if (saveSources)
    {
        QFile   sourcesFile(_S(":/sources/sources/sources.7z"));
        if(!sourcesFile.open(QFile::ReadOnly))
        {
            qDebug() << _T("%1 Ошибка доступа к исходникам: %2")
                        .arg(posForLog)
                        .arg(sourcesFile.errorString());
            return 1;
        }

        QFile   resultFile(_S("sources.7z"));
        if(!resultFile.open(QFile::WriteOnly))
        {
            qDebug() << _T("%1 Ошибка создания файла для сохранения: %2")
                        .arg(posForLog)
                        .arg(resultFile.errorString());
            return 1;
        }

        resultFile.write(sourcesFile.readAll());
        resultFile.close();
        sourcesFile.close();

        qDebug()<<"Исходники сохранены в файле sources.7z";
        return 0;
    }

    if (showHelp)
    {
        QFile   helpFile(_S(":/texts/texts/help.txt"));
        helpFile.open(QFile::ReadOnly);
        QString helpText = helpFile.readAll();
        qDebug() << _T("jPOS версия от %1 %2").arg(BUILDDATE).arg(BUILDTIME)<<endl;
        qDebug() << helpText;
        return 0;
    }

    if (newlog)
    {
        QFile::remove(logFileName);
    }


    if (!logFileName.isEmpty())
        qInstallMessageHandler(fileMessageHandler);
    //else
    //    qInstallMessageHandler(outputMessageHandler);


    if(!stylefree)
    {
        QFile styleFile;
开发者ID:dmitry-aka-jok,项目名称:jpos2,代码行数:67,代码来源:main.cpp

示例10: urlstr

MainWindow::MainWindow(char *urlx):iskeyboardshow(false)
{
    setWindowFlags(Qt::WindowStaysOnTopHint);
    this->showFullScreen();
//    this->setWindowFlags(Qt::WindowCloseButtonHint);
//    setWindowFlags(Qt::Tool | Qt::FramelessWindowHint);   // 隐藏标题栏己周围框架
//    this->setAttribute(Qt::WA_TranslucentBackground, true);        // 设置背景透明(version >= QT4.5)
//    this->setAttribute(Qt::WA_NoSystemBackground, true);
//    this->setAttribute(Qt::WA_NoBackground, true);
//    QPalette pal = palette();
//    pal.setColor(QPalette::Background, QColor(0x00,0x00,0x00,0x00));
//    this->setPalette(pal);
//    QMessageBox::warning(NULL,"MainWindow",QString("%1").arg((this->centralWidget() == 0)?"nil":"have"));
//    qApp->setStyleSheet("QMainWindow {background-image: url(:/images/111.png);}");

    frm = new QFrame();
    keyboardfrm = new mainForm;
    webView = new WebView(frm);
    pbExit = new QPushButton(frm);
    pbInput = new QPushButton(frm);

//    pbInput->setCheckable(true);

//    keyboardfrm->setAttribute(Qt::WA_TranslucentBackground, false);

    //webView->load(QUrl("http://10.6.14.60:8080/hipicd/cube/index.html"));
   // webView->load(QUrl("http://www.baidu.com"));

    if(NULL != urlx)
    {
        QString urlstr(urlx);

        if (-1 != urlstr.indexOf(QRegExp("[Ff][Ii][Ll][Ee]"),0))
        {
            qDebug() << "localfile: " << urlstr;
            webView->load(QUrl::fromLocalFile( urlstr));
        }
        else if (-1 == urlstr.indexOf(QRegExp("[Hh][Tt][Tt][Pp]"),0))
        {
            urlstr.prepend("http://");
        }


//        QMessageBox::warning(NULL, "error", urlstr);
        webView->load(QUrl(urlstr));
    }
    else
    {
        webView->load(QUrl("http://resource.hipidata.cn/web/s_index.html"));
    }


 
    webPage = webView->page();


//    webHistory = webPage->history();
    //webView->setD

//    urlAddr = new QLineEdit;
//    statusLabel = new QLabel;
//    progressBar = new QProgressBar;

    dockWidget = new QDockWidget();
    dockWidget->setFocusPolicy(Qt::NoFocus);
    dockWidget->setFocusProxy(0);
    dockWidget->setAllowedAreas(Qt::BottomDockWidgetArea);
    dockWidget->setFeatures(QDockWidget::DockWidgetClosable);
    this->setCorner(Qt::BottomLeftCorner, Qt::BottomDockWidgetArea);
//    dockWidget->setFloating(true);


	//ldockWidget = new QDockWidget();
	
	
	
    QFile file;
    file.setFileName(":/myjquery.js");
    file.open(QIODevice::ReadOnly);
    this->jQuery = file.readAll();
    file.close();


	//QMessageBox::about(this,jQuery,this->jQuery);
	//webPage->currentFrame()->evaluateJavaScript(jQuery);
	

//    createActions();
    //createMenus();
    //createToolBars();
    createCentralWidget();

//    createStatusBar();
    createKeyBoardDock();
//    createHeader();
   // createLeftDock();
    setKeyBoardDockShow(false);

    webPage->setLinkDelegationPolicy(QWebPage::DelegateAllLinks);

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

示例11: ContinueLocalStorageChecking

	void Syncer::ContinueLocalStorageChecking ()
	{
		if (Paths_.isEmpty ())
		{
			//TODO checking finished
			qDebug () << "finished";
			return;
		}

		QString path = Paths_.takeAt (0);
		QFileInfo info (path);
		DriveItem parentItem = RealPath2Item_.value (info.dir ().absolutePath ());

		bool found = false;
		DriveItem currentItem;
		for (const auto& item : Items_)
		{
			if (item.IsFolder_ != info.isDir () ||
					item.Name_ != info.fileName () ||
					item.Labels_ & DriveItem::ILRemoved ||
					item.ParentId_ != parentItem.Id_)
				continue;

			currentItem = item;
			found = true;
			Items_.removeOne (item);
			break;
		}

		if (found)
		{
			if (QFileInfo (path).exists ())
			{
				RealPath2Item_ [path] = currentItem;
				if (!info.isDir ())
				{
					QFile file (path);
					if (file.open (QIODevice::ReadOnly))
					{
						if (currentItem.Md5_ != QCryptographicHash::hash (file.readAll (), QCryptographicHash::Md5).toHex ())
						{
							//TODO update
							qDebug () << currentItem.Id_ << currentItem.Name_ << "need update";
						}
					}
				}
			}
			else
				DM_->MoveEntryToTrash (currentItem.Id_);
			ContinueLocalStorageChecking ();
		}
		else
		{
			connect (DM_,
					SIGNAL (gotNewItem (DriveItem)),
					this,
					SLOT (handleGotNewItem (DriveItem)));
			RealPathQueue_ << path;
			!info.isDir () ?
				DM_->Upload (path, QStringList () << parentItem.Id_) :
				DM_->CreateDirectory (info.fileName (), parentItem.Id_);
		}
	}
开发者ID:ForNeVeR,项目名称:leechcraft,代码行数:63,代码来源:syncer.cpp

示例12: createRequiredFiles

void PlasmoidHandler::createRequiredFiles(const QString &serviceType, const QString &pluginName,
                                         const QString &userName, const QString &userEmail, const QString &fileExtension)
{
    // a package may require a file like ui/main.qml
    // but the ui dir may not be required, so lets check for them
    for (const auto &it : package().requiredFiles()) {
        if (m_directoryDefinitions.values().contains(it)) {
            const QString dirName(m_directoryDefinitions.key(it));
            QDir dir(packagePath() + contentsPrefix());
            dir.mkpath(dirName);
            dir.cd(dirName);

            QFile f;
            const QString filePath = dir.path() + QLatin1Char('/') +
                                 m_fileDefinitions[it];
            QString templateFilePath;

            if (it == QLatin1String("mainscript")) {
                if (serviceType == "Plasma/Applet") {
                    templateFilePath.append("mainPlasmoid");
                } else if (serviceType == "KWin/WindowSwitcher") {
                    templateFilePath.append("mainTabbox");
                } else if (serviceType == "KWin/Script") {
                    templateFilePath.append("mainKWinScript");
                } else if (serviceType == "KWin/Effect") {
                    templateFilePath.append("mainKWinEffect");
                }
                f.setFileName(QStandardPaths::locate(QStandardPaths::DataLocation,
                                                 QStringLiteral("templates/") + templateFilePath + fileExtension));

                const bool ok = f.copy(filePath);
                if (!ok) {
                    emit error(QStringLiteral("The mainscript file hasn't been created"));
                }

                f.setFileName(filePath);
                f.open(QIODevice::ReadWrite);

                // Now open these files, and substitute the main class, author, email and date fields
                QByteArray tmpPluginName(pluginName.toLocal8Bit());
                QByteArray tmpAuthor(userName.toLocal8Bit());
                QByteArray tmpEmail(userEmail.toLocal8Bit());
                QByteArray rawData = f.readAll();
                f.close();
                f.open(QIODevice::WriteOnly);

                QByteArray replacedString("$PLASMOID_NAME");
                if (rawData.contains(replacedString)) {
                    rawData.replace(replacedString, tmpPluginName);
                }
                replacedString.clear();

                replacedString.append("$AUTHOR");
                if (rawData.contains(replacedString)) {
                    rawData.replace(replacedString, tmpAuthor);
                }
                replacedString.clear();

                replacedString.append("$EMAIL");
                if (rawData.contains(replacedString)) {
                    rawData.replace(replacedString, tmpEmail);
                }
                replacedString.clear();

                replacedString.append("$DATE");
                QDate date = QDate::currentDate();
                QByteArray datetime(date.toString().toUtf8());
                QTime time = QTime::currentTime();
                datetime.append(", " + time.toString().toUtf8());
                if (rawData.contains(replacedString)) {
                    rawData.replace(replacedString, datetime);
                }

                f.write(rawData);
                f.close();
            }
        }
    }

    loadPackage();
}
开发者ID:KDE,项目名称:plasma-sdk,代码行数:81,代码来源:plasmoidhandler.cpp

示例13: ui_style

Application::Application(int &argc, char **argv) : QApplication(argc,argv)
{
	QTranslator *main_translator=nullptr, *plugin_translator=nullptr;
	QFile ui_style(GlobalAttributes::TMPL_CONFIGURATIONS_DIR +
				   GlobalAttributes::DIR_SEPARATOR +
				   GlobalAttributes::UI_STYLE_CONF +
				   GlobalAttributes::CONFIGURATION_EXT);
	QString plugin_name, plug_lang_dir, plug_lang_file;
	QStringList dir_list;
	QDir dir;

	//Creating the initial user's configuration
	createUserConfiguration();

	//Changing the current working dir to the executable's directory in
	QDir::setCurrent(this->applicationDirPath());

	//Adding paths which executable will find plugins and it's dependecies
	this->addLibraryPath(this->applicationDirPath());
	this->addLibraryPath(GlobalAttributes::PLUGINS_DIR);

	//Try to create plugins dir if it does not exists
	if(!dir.exists(GlobalAttributes::PLUGINS_DIR))
	{
		if(!dir.mkdir(GlobalAttributes::PLUGINS_DIR))
		{
			Messagebox msg;
			msg.show(Exception(Exception::getErrorMessage(ERR_FILE_DIR_NOT_WRITTEN).arg(GlobalAttributes::PLUGINS_DIR),
							   ERR_FILE_DIR_NOT_WRITTEN,__PRETTY_FUNCTION__,__FILE__,__LINE__));
		}
	}

	//Check if the temporary dir exists, if not, creates it.
	if(!dir.exists(GlobalAttributes::TEMPORARY_DIR))
	{
		if(!dir.mkdir(GlobalAttributes::TEMPORARY_DIR))
		{
			Messagebox msg;
			msg.show(Exception(Exception::getErrorMessage(ERR_FILE_DIR_NOT_WRITTEN).arg(GlobalAttributes::TEMPORARY_DIR),
							   ERR_FILE_DIR_NOT_WRITTEN, __PRETTY_FUNCTION__,__FILE__,__LINE__));
		}
	}

	//Trying to identify if the user defined a custom UI language in the pgmodeler.conf file
	QString conf_file =	GlobalAttributes::CONFIGURATIONS_DIR +
											GlobalAttributes::DIR_SEPARATOR +
											GlobalAttributes::GENERAL_CONF +
											GlobalAttributes::CONFIGURATION_EXT;
	QFile input;
	QString lang_id = QLocale::system().name();

	input.setFileName(conf_file);

	if(input.open(QFile::ReadOnly))
	{
		QString buf = QString(input.readAll());
		QRegExp regexp = QRegExp(QString("(%1)(.*)(=)(\\\")(.)+(\\\")(\\\n)").arg(ParsersAttributes::UI_LANGUAGE));
		int idx =	regexp.indexIn(QString(buf));

		//Extract the value of the ui-language attribute in the conf file
		lang_id = buf.mid(idx, regexp.matchedLength());
		lang_id.remove(ParsersAttributes::UI_LANGUAGE);
		lang_id.remove(QChar('"')).remove(QChar('=')).remove(QChar('\n'));
	}

	//Tries to load the main ui translation according to the system's locale
	main_translator=new QTranslator(this);
	main_translator->load(lang_id, GlobalAttributes::LANGUAGES_DIR);
	this->installTranslator(main_translator);

	//Trying to load plugins translations
	dir_list=QDir(GlobalAttributes::PLUGINS_DIR +
								GlobalAttributes::DIR_SEPARATOR,
								QString("*"), QDir::Name, QDir::AllDirs | QDir::NoDotAndDotDot).entryList();

	while(!dir_list.isEmpty())
	{
		plugin_name=dir_list.front();
		dir_list.pop_front();

		//Configure the path to "lang" subdir at current plugin directory
		plug_lang_dir=GlobalAttributes::PLUGINS_DIR +
					  GlobalAttributes::DIR_SEPARATOR + plugin_name +
					  GlobalAttributes::DIR_SEPARATOR + QString("lang") +
					  GlobalAttributes::DIR_SEPARATOR;

		plug_lang_file=plugin_name + QString(".") + lang_id;

		//Check if the .qm file exists for the current plugin. If so create and install a translator
		if(QFileInfo(plug_lang_dir + plug_lang_file + QString(".qm")).exists())
		{
			plugin_translator=new QTranslator(this);
			plugin_translator->load(plug_lang_file, plug_lang_dir);
			this->installTranslator(plugin_translator);
		}
	}

	//Loading app style sheet
	ui_style.open(QFile::ReadOnly);

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

示例14: initShaders

void MyWindow::initShaders()
{
    QOpenGLShader vShader(QOpenGLShader::Vertex);
    QOpenGLShader fShader(QOpenGLShader::Fragment);    
    QFile         shaderFile;
    QByteArray    shaderSource;

    // Shader color
    shaderFile.setFileName(":/vshader_col.txt");
    shaderFile.open(QIODevice::ReadOnly);
    shaderSource = shaderFile.readAll();
    shaderFile.close();
    qDebug() << "vertex \"color\" compile: " << vShader.compileSourceCode(shaderSource);

    shaderFile.setFileName(":/fshader_col.txt");
    shaderFile.open(QIODevice::ReadOnly);
    shaderSource = shaderFile.readAll();
    shaderFile.close();
    qDebug() << "frag   \"color\" compile: " << fShader.compileSourceCode(shaderSource);

    mProgramCol = new (QOpenGLShaderProgram);
    mProgramCol->addShader(&vShader);
    mProgramCol->addShader(&fShader);
    qDebug() << "shader \"color\" link: " << mProgramCol->link();

    // Shader normal
    shaderFile.setFileName(":/vshader_norm.txt");
    shaderFile.open(QIODevice::ReadOnly);
    shaderSource = shaderFile.readAll();
    shaderFile.close();
    qDebug() << "vertex \"normal\" compile: " << vShader.compileSourceCode(shaderSource);

    shaderFile.setFileName(":/fshader_norm.txt");
    shaderFile.open(QIODevice::ReadOnly);
    shaderSource = shaderFile.readAll();
    shaderFile.close();
    qDebug() << "frag   \"normal\" compile: " << fShader.compileSourceCode(shaderSource);

    mProgramNorm = new (QOpenGLShaderProgram);
    mProgramNorm->addShader(&vShader);
    mProgramNorm->addShader(&fShader);
    qDebug() << "shader \"normal\" link: " << mProgramNorm->link();

    // Shader texture
    shaderFile.setFileName(":/vshader_tex.txt");
    shaderFile.open(QIODevice::ReadOnly);
    shaderSource = shaderFile.readAll();
    shaderFile.close();
    qDebug() << "vertex \"texture\" compile: " << vShader.compileSourceCode(shaderSource);

    shaderFile.setFileName(":/fshader_tex.txt");
    shaderFile.open(QIODevice::ReadOnly);
    shaderSource = shaderFile.readAll();
    shaderFile.close();
    qDebug() << "frag   \"texture\" compile: " << fShader.compileSourceCode(shaderSource);

    mProgramTex = new (QOpenGLShaderProgram);
    mProgramTex->addShader(&vShader);
    mProgramTex->addShader(&fShader);
    qDebug() << "shader \"texture\" link: " << mProgramTex->link();
}
开发者ID:Imarion,项目名称:VertexRefactoring,代码行数:61,代码来源:Triangle.cpp

示例15: main

int main(int argc, char **argv)
{
    QCoreApplication application(argc, argv);
    application.setOrganizationName("CutePaste");
    application.setApplicationName("CutePaste Desktop Console Frontend");

    QTextStream standardOutputStream(stdout);
    QFile dataFile;
    QString firstArgument = QCoreApplication::arguments().size() < 2 ? QString() : QCoreApplication::arguments().at(1);
    if (!firstArgument.isEmpty()) {
        dataFile.setFileName(firstArgument);
        dataFile.open(QIODevice::ReadOnly);
    } else {
        dataFile.open(stdin, QIODevice::ReadOnly);
    }

    QByteArray pasteTextByteArray = dataFile.readAll();

    QJsonObject requestJsonObject;
    requestJsonObject.insert(QStringLiteral("data"), QString::fromUtf8(pasteTextByteArray));
    requestJsonObject.insert(QStringLiteral("language"), QStringLiteral("text"));

    QJsonDocument requestJsonDocument(requestJsonObject);

    QString baseUrlString = QStringLiteral("http://pastebin.kde.org");

    QNetworkRequest networkRequest;
    networkRequest.setAttribute(QNetworkRequest::DoNotBufferUploadDataAttribute, true);
    networkRequest.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
    networkRequest.setUrl(QUrl(baseUrlString + "/api/json/create"));

    QNetworkAccessManager networkAccessManager;
    QScopedPointer<QNetworkReply> networkReplyScopedPointer(networkAccessManager.post(networkRequest, requestJsonDocument.toJson()));
    QObject::connect(networkReplyScopedPointer.data(), &QNetworkReply::finished, [&]() {

        QJsonParseError jsonParseError;
        QByteArray replyJsonByteArray = networkReplyScopedPointer->readAll();
        QJsonDocument replyJsonDocument = QJsonDocument::fromJson(replyJsonByteArray, &jsonParseError);
        if (jsonParseError.error != QJsonParseError::NoError) {
            qDebug() << "The json network reply is not valid json:" << jsonParseError.errorString();
            QCoreApplication::quit();
        }

        if (!replyJsonDocument.isObject()) {
            qDebug() << "The json network reply is not an object";
            QCoreApplication::quit();
        }
        
        QJsonObject replyJsonObject = replyJsonDocument.object();
        QJsonValue resultValue = replyJsonObject.value(QStringLiteral("result"));

        if (!resultValue.isObject()) {
            qDebug() << "The json network reply does not contain an object for the \"result\" key";
            QCoreApplication::quit();
        }

        QJsonValue identifierValue = resultValue.toObject().value(QStringLiteral("id"));

        if (!identifierValue.isString()) {
            qDebug() << "The json network reply does not contain a string for the \"id\" key";
            QCoreApplication::quit();
        }

        endl(standardOutputStream << baseUrlString << '/' << identifierValue.toString());

        QCoreApplication::quit();
    });

    QObject::connect(networkReplyScopedPointer.data(), static_cast<void (QNetworkReply::*)(QNetworkReply::NetworkError)>(&QNetworkReply::error), [&](QNetworkReply::NetworkError networkReplyError) {
        if (networkReplyError != QNetworkReply::NoError)
            endl(standardOutputStream << networkReplyScopedPointer->errorString());
    });

    QObject::connect(networkReplyScopedPointer.data(), &QNetworkReply::sslErrors, [&](QList<QSslError> networkReplySslErrors) {
        if (!networkReplySslErrors.isEmpty()) {
            foreach (const QSslError &networkReplySslError, networkReplySslErrors)
                endl(standardOutputStream << networkReplySslError.errorString());
        }
    });
开发者ID:netrunner-debian-kde-extras,项目名称:cutepaste,代码行数:79,代码来源:main.cpp


注:本文中的QFile::readAll方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。