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


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

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


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

示例1: importXML

void DistroMesas::importXML(const QString val) {
  QFile file ( g_confpr->value( CONF_DIR_USER ) + "distromesas_" + mainCompany()->dbName() + ".cfn" );

    if (file.exists()) {
        if ( !file.open ( QIODevice::ReadOnly ) ) {
            
            return;
        } // end if
        QString result (file.readAll());
        file.close(); 


    QDomDocument doc ( "mydocument" );

    if ( !doc.setContent ( result ) ) {
	
        return;
    } // end if

    QDomElement docElem = doc.documentElement();
    QDomElement principal = docElem.firstChildElement ( "BACKGROUND" );
    m_background = principal.text();

    principal = docElem.firstChildElement ( "ESCALA" );
    g_escala = principal.text().toInt();


    QDomNodeList nodos = docElem.elementsByTagName ( "MESA" );
    int i = 0;
    while (i < nodos.count() ) {
        QDomNode ventana = nodos.item ( i++ );
        QDomElement e1 = ventana.toElement(); /// try to convert the node to an element.
        if ( !e1.isNull() ) { /// the node was really an element.
            QString nodoText = e1.text();
            /// Pasamos el XML a texto para poder procesarlo como tal.
            QString result;
            QTextStream stream ( &result );
            ventana.save(stream,5);

            Mesa *mesa = new Mesa((BtCompany *) mainCompany(), mui_widget);
            mesa->importXML(result);
	    
	    if (! m_listapantallas.contains(mesa->m_pantalla)) {
	        if (m_pantallaactual == "") {
		    m_pantallaactual = mesa->m_pantalla;
		} // end if
		m_listapantallas.append(mesa->m_pantalla);
		QToolButton *but = new QToolButton(this);
		but->setObjectName("p_"+mesa->m_pantalla);
		but->setText(mesa->m_pantalla);
		but->setMinimumHeight(42);
		but->setMinimumWidth(42);
		but->setCheckable(TRUE);
		mui_espaciopantallas->addWidget(but);
		connect(but, SIGNAL(clicked()), this, SLOT(cambiarPantalla()));
	    } // end if
	    if (mesa->m_pantalla == m_pantallaactual) 
		mesa->show();

        } // end if
    } // end while

} // end if

}
开发者ID:trifolio6,项目名称:Bulmages,代码行数:65,代码来源:mesas.cpp

示例2: read

bool MachConf::read()
 {
     QString errorStr;
     int errorLine;
     int errorColumn;
     QFile *device = new QFile(_fileName);
     if (!device->open(QIODevice::ReadOnly))
        return false;
     if (!domDocument.setContent(device, true, &errorStr, &errorLine,
                                 &errorColumn)) {

         return false;
     }

     QDomElement root = domDocument.documentElement();

    //Console *console =
     //cout <<
     //std::basic_ostream<<root.tagName()<<endl;

    Console * console = SkyMain::getUartConsole();
    DevTreeView *treeView = SkyMain::getDevTreeView();

    //QDomElement child = root.firstChildElement("arch");
    if(root.tagName() != "machine"){        
         return false;
    }
    else{
        QDomAttr attr = root.attributeNode(QString("name"));
        treeView->insertMachine(attr.value());
    }
    QDomElement board = root.firstChildElement("board");

    //console->insertPlainText(attr.value());
    console->insertPlainText("\n");
    //console->insertPlainText(child);

    //console->insertPlainText(QString("ljklkjkejlwer"));

       /*
     if (root.tagName() != "xbel") {
         QMessageBox::information(window(), tr("DOM Bookmarks"),
                                  tr("The file is not an XBEL file."));
         return false;
     } else if (root.hasAttribute("version")
                && root.attribute("version") != "1.0") {
         QMessageBox::information(window(), tr("DOM Bookmarks"),
                                  tr("The file is not an XBEL version 1.0 "
                                     "file."));
         return false;
     }

     clear();

     disconnect(this, SIGNAL(itemChanged(QTreeWidgetItem *, int)),
                this, SLOT(updateDomElement(QTreeWidgetItem *, int)));

     QDomElement child = root.firstChildElement("folder");
     while (!child.isNull()) {
         parseFolderElement(child);
         child = child.nextSiblingElement("folder");
     }

     connect(this, SIGNAL(itemChanged(QTreeWidgetItem *, int)),
             this, SLOT(updateDomElement(QTreeWidgetItem *, int)));
    */
     return true;
}
开发者ID:Jarvishappy,项目名称:tsinghua,代码行数:68,代码来源:machconf.cpp

示例3: if

//---------------------------------------------------------------------------------
void
MagicRules::initialize(const QString& p_jsonFile)
{
    // Read the JSON file
    QString val;
    QFile file;
    file.setFileName(p_jsonFile);
    file.open(QIODevice::ReadOnly | QIODevice::Text);
    val = file.readAll();
    file.close();

    // Read document
    QJsonParseError error;
    QJsonDocument doc = QJsonDocument::fromJson(val.toUtf8(), &error);
    if (error.error != QJsonParseError::NoError)
    {
        qCritical() << QString("Error while reading file: %1\nError: %2").arg(p_jsonFile, error.errorString());
        return;
    }

    // Parse each magic type and add to the rules
    QJsonArray magicTypesArray = doc.object().value("magic_types").toArray();
    QJsonObject currentType;
    MagicTypeDefinition* typeDef = 0;
    MagicTypePriorityDefinition* prioDef = 0;
    QJsonArray tempArray;
    QJsonObject tempObject;
    QJsonObject tempObject2;
    for (int i = 0; i < magicTypesArray.size(); ++i)
    {
        currentType = magicTypesArray.at(i).toObject();

        // Add type definition
        typeDef = new MagicTypeDefinition();

        // Translations
        tempObject = currentType["translations"].toObject();
        for (int j = 0; j < tempObject.keys().size(); ++j)
        {
            typeDef->translations[tempObject.keys().at(j)] = tempObject[tempObject.keys().at(j)].toString();
        }

        // Types
        tempArray = currentType["types"].toArray();
        for (int j = 0; j < tempArray.size(); ++j)
        {
            typeDef->types.push_back(tempArray.at(j).toString());
        }

        // Priorities
        tempObject = currentType["priorities"].toObject();
        for (int j = 0; j < tempObject.keys().size(); ++j)
        {
            tempObject2 = tempObject[tempObject.keys().at(j)].toObject();

            prioDef = new MagicTypePriorityDefinition();

            // Starting magic
            if (tempObject2.contains("starting_magic"))
            {
                prioDef->startingMagic = tempObject2.value("starting_magic").toString().toInt();
            }

            // Free spells
            if (tempObject2.contains("free_spells"))
            {
                prioDef->freeSpells = tempObject2.value("free_spells").toString().toInt();
            }

            // Free skills
            if (tempObject2.contains("free_skills"))
            {
                prioDef->freeSkills.first = tempObject2.value("free_skills").toArray().at(0).toString().toInt();
                prioDef->freeSkills.second = tempObject2.value("free_skills").toArray().at(1).toString().toInt();
            }

            // Forced skill group
            if (tempObject2.contains("free_skill_groups"))
            {
                prioDef->freeSkillGroup.first = tempObject2.value("free_skill_groups").toArray().at(0).toString().toInt();
                prioDef->freeSkillGroup.second = tempObject2.value("free_skill_groups").toArray().at(1).toString().toInt();
            }

            // Store priority
            typeDef->priorities[tempObject.keys().at(j).toInt()] = prioDef;
        }

        // Make sure the definition doesn't already exist
        if (_typeDefinitions.contains(currentType["unique_id"].toString()))
        {
            qCritical() << "Magic type \"" << currentType["unique_id"].toString() << "\" already exists. Parsing aborted.";
            return;
        }

        _typeDefinitions[currentType["unique_id"].toString()] = typeDef;
    }// END magic types

    // Parse spell category strings
    QJsonArray categoryArray = doc.object().value("spell_categories").toArray();
//.........这里部分代码省略.........
开发者ID:TheSHEEEP,项目名称:SR5-Shaman,代码行数:101,代码来源:magicrules.cpp

示例4: dragResource

void jsBridge::dragResource(QString hash) {

    Resource *res = Resource::fromHash(hash);
    if (res == NULL)
        return;

    QString mime = res->mimeType();
    QString fileName = res->getFileName();
    QByteArray data = res->getData();

    QPixmap pix;
    if (res->isImage()) {
        pix.loadFromData(data);
    } else if (res->isPDF()) {
        pix.load(":/img/application-pdf.png");
    } else {
        pix.load(":/img/application-octet-stream.png");
    }

    delete res;

    if (fileName.isEmpty())
        fileName = hash;

    if (mime == "application/pdf") {
        if (!fileName.endsWith(".pdf", Qt::CaseInsensitive))
            fileName += ".pdf";
    } else if (mime == "image/jpeg") {
        if (!fileName.endsWith(".jpg", Qt::CaseInsensitive) && !fileName.endsWith(".jpeg", Qt::CaseInsensitive))
            fileName += ".jpg";
    } else if (mime == "image/png") {
        if (!fileName.endsWith(".png", Qt::CaseInsensitive))
            fileName += ".png";
    } else if (mime == "image/gif") {
        if (!fileName.endsWith(".gif", Qt::CaseInsensitive))
            fileName += ".gif";
    }

    QString tmpl = QDir::tempPath() + QDir::separator() + fileName;

    QFile* f = new QFile(tmpl);

    if (!f->open(QIODevice::WriteOnly))
        return;

    f->write(data);
    f->close();
    files.enqueue(f);

    QTimer::singleShot(60000, this, SLOT(removeTmpFile()));

    QDrag *drag = new QDrag(new QWidget());
    QMimeData *mimeData = new QMimeData;

    QFileInfo fileInfo(tmpl);
    QUrl url = QUrl::fromLocalFile(fileInfo.absoluteFilePath());
    mimeData->setUrls(QList<QUrl>() << url);

    drag->setMimeData(mimeData);

    if (!pix.isNull())
        drag->setPixmap(pix.scaled(128,128, Qt::KeepAspectRatio, Qt::SmoothTransformation));

    drag->exec(Qt::CopyAction | Qt::MoveAction);
}
开发者ID:MidoriYakumo,项目名称:hippo,代码行数:65,代码来源:jsbridge.cpp

示例5: htmlizedTextPart

QString htmlizedTextPart(const QModelIndex &partIndex, const QFontInfo &font, const QColor &backgroundColor, const QColor &textColor,
                         const QColor &linkColor, const QColor &visitedLinkColor)
{
    static const QString defaultStyle = QString::fromUtf8(
        "pre{word-wrap: break-word; white-space: pre-wrap;}"
        // The following line, sadly, produces a warning "QFont::setPixelSize: Pixel size <= 0 (0)".
        // However, if it is not in place or if the font size is set higher, even to 0.1px, WebKit reserves space for the
        // quotation characters and therefore a weird white area appears. Even width: 0px doesn't help, so it looks like
        // we will have to live with this warning for the time being.
        ".quotemarks{color:transparent;font-size:0px;}"

        // Cannot really use the :dir(rtl) selector for putting the quote indicator to the "correct" side.
        // It's CSS4 and it isn't supported yet.
        "blockquote{font-size:90%; margin: 4pt 0 4pt 0; padding: 0 0 0 1em; border-left: 2px solid %1; unicode-bidi: -webkit-plaintext}"

        // Stop the font size from getting smaller after reaching two levels of quotes
        // (ie. starting on the third level, don't make the size any smaller than what it already is)
        "blockquote blockquote blockquote {font-size: 100%}"
        ".signature{opacity: 0.6;}"

        // Dynamic quote collapsing via pure CSS, yay
        "input {display: none}"
        "input ~ span.full {display: block}"
        "input ~ span.short {display: none}"
        "input:checked ~ span.full {display: none}"
        "input:checked ~ span.short {display: block}"
        "label {border: 1px solid %2; border-radius: 5px; padding: 0px 4px 0px 4px; white-space: nowrap}"
        // BLACK UP-POINTING SMALL TRIANGLE (U+25B4)
        // BLACK DOWN-POINTING SMALL TRIANGLE (U+25BE)
        "span.full > blockquote > label:before {content: \"\u25b4\"}"
        "span.short > blockquote > label:after {content: \" \u25be\"}"
        "span.shortquote > blockquote > label {display: none}"
    );

    QString fontSpecification(QStringLiteral("pre{"));
    if (font.italic())
        fontSpecification += QLatin1String("font-style: italic; ");
    if (font.bold())
        fontSpecification += QLatin1String("font-weight: bold; ");
    fontSpecification += QStringLiteral("font-size: %1px; font-family: \"%2\", monospace }").arg(
                QString::number(font.pixelSize()), font.family());

    QString textColors = QString::fromUtf8("body { background-color: %1; color: %2 }"
                                           "a:link { color: %3 } a:visited { color: %4 } a:hover { color: %3 }").arg(
                backgroundColor.name(), textColor.name(), linkColor.name(), visitedLinkColor.name());
    // looks like there's no special color for hovered links in Qt

    // build stylesheet and html header
    QColor tintForQuoteIndicator = backgroundColor;
    tintForQuoteIndicator.setAlpha(0x66);
    static QString stylesheet = defaultStyle.arg(linkColor.name(),
                                                 tintColor(textColor, tintForQuoteIndicator).name());
    static QFile file(Common::writablePath(Common::LOCATION_DATA) + QLatin1String("message.css"));
    static QDateTime lastVersion;
    QDateTime lastTouched(file.exists() ? QFileInfo(file).lastModified() : QDateTime());
    if (lastVersion < lastTouched) {
        stylesheet = defaultStyle;
        if (file.open(QIODevice::ReadOnly | QIODevice::Text)) {
            const QString userSheet = QString::fromLocal8Bit(file.readAll().data());
            lastVersion = lastTouched;
            stylesheet += QLatin1Char('\n') + userSheet;
            file.close();
        }
    }

    // The dir="auto" is required for WebKit to treat all paragraphs as entities with possibly different text direction.
    // The individual paragraphs unfortunately share the same text alignment, though, as per
    // https://bugs.webkit.org/show_bug.cgi?id=71194 (fixed in Blink already).
    QString htmlHeader(QLatin1String("<html><head><style type=\"text/css\"><!--") + textColors + fontSpecification + stylesheet +
                       QLatin1String("--></style></head><body><pre dir=\"auto\">"));
    static QString htmlFooter(QStringLiteral("\n</pre></body></html>"));


    // We cannot rely on the QWebFrame's toPlainText because of https://bugs.kde.org/show_bug.cgi?id=321160
    QString markup = plainTextToHtml(partIndex.data(Imap::Mailbox::RolePartUnicodeText).toString(), flowedFormatForPart(partIndex));

    return htmlHeader + markup + htmlFooter;
}
开发者ID:ChristopherCotnoir,项目名称:trojita,代码行数:78,代码来源:PlainTextFormatter.cpp

示例6: savedFileForSnapshot

QFile* Snapshot::savedFileForSnapshot(bool isTemporary) {
    auto glCanvas = DependencyManager::get<GLCanvas>();
    QImage shot = glCanvas->grabFrameBuffer();
    
    Avatar* avatar = Application::getInstance()->getAvatar();
    
    glm::vec3 location = avatar->getPosition();
    glm::quat orientation = avatar->getHead()->getOrientation();
    
    // add metadata
    shot.setText(LOCATION_X, QString::number(location.x));
    shot.setText(LOCATION_Y, QString::number(location.y));
    shot.setText(LOCATION_Z, QString::number(location.z));
    
    shot.setText(ORIENTATION_X, QString::number(orientation.x));
    shot.setText(ORIENTATION_Y, QString::number(orientation.y));
    shot.setText(ORIENTATION_Z, QString::number(orientation.z));
    shot.setText(ORIENTATION_W, QString::number(orientation.w));
    
    shot.setText(DOMAIN_KEY, DependencyManager::get<NodeList>()->getDomainHandler().getHostname());

    QString formattedLocation = QString("%1_%2_%3").arg(location.x).arg(location.y).arg(location.z);
    // replace decimal . with '-'
    formattedLocation.replace('.', '-');
    
    QString username = AccountManager::getInstance().getAccountInfo().getUsername();
    // normalize username, replace all non alphanumeric with '-'
    username.replace(QRegExp("[^A-Za-z0-9_]"), "-");
    
    QDateTime now = QDateTime::currentDateTime();
    
    QString filename = FILENAME_PATH_FORMAT.arg(username, now.toString(DATETIME_FORMAT), formattedLocation);
    
    const int IMAGE_QUALITY = 100;
    
    if (!isTemporary) {
        QString snapshotFullPath = Menu::getInstance()->getSnapshotsLocation();
        
        if (!snapshotFullPath.endsWith(QDir::separator())) {
            snapshotFullPath.append(QDir::separator());
        }
        
        snapshotFullPath.append(filename);
        
        QFile* imageFile = new QFile(snapshotFullPath);
        imageFile->open(QIODevice::WriteOnly);
        
        shot.save(imageFile, 0, IMAGE_QUALITY);
        imageFile->close();
        
        return imageFile;
    } else {
        QTemporaryFile* imageTempFile = new QTemporaryFile(QDir::tempPath() + "/XXXXXX-" + filename);
        
        if (!imageTempFile->open()) {
            qDebug() << "Unable to open QTemporaryFile for temp snapshot. Will not save.";
            return NULL;
        }
        
        shot.save(imageTempFile, 0, IMAGE_QUALITY);
        imageTempFile->close();
        
        return imageTempFile;
    }
}
开发者ID:ey6es,项目名称:hifi,代码行数:65,代码来源:Snapshot.cpp

示例7: myFile

Sequence::Sequence(
                        //CAMERASET
                          QString INPUT_PATH_CAMERA_SET_IN,

                        //MODEL
                          QString INPUT_BasePath_OutPut_IN,
                          QString INPUT_dynamicStringPart_IN,
                          QString INPUT_EXTENSSS_Mesh_IN,
                          QString INPUT_EXTENSSS_Skeleton_IN,
                          QString INPUT_EXTENSSS_Skin_IN,
                          QString INPUT_PATH_MODELS_INFO_IN,

                        //ANIMATION
                          QString PATH_OutputBase_IN,
                          QString PATH_FolderName_INPUT_IN,
                          QString INPUT_EXTENSSS_Motion_IN,
                          QString PATH_INDEX_BOUNDS_IN,

                        //SEQUENCE
                          QString PATH_INDEX_BOUNDS_INNN,
                          QString RadioSequenceID_String_IN,

                          bool printEnabled
                  )
{

        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

        cameraSet = CameraSet( INPUT_PATH_CAMERA_SET_IN );

        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

        Animation animSource = Animation(
                                              //MODEL
                                                INPUT_BasePath_OutPut_IN,
                                                INPUT_dynamicStringPart_IN,
                                                INPUT_EXTENSSS_Mesh_IN,
                                                INPUT_EXTENSSS_Skeleton_IN,
                                                INPUT_EXTENSSS_Skin_IN,
                                                INPUT_PATH_MODELS_INFO_IN,

                                              //ANIMATION
                                                PATH_OutputBase_IN,
                                                PATH_FolderName_INPUT_IN,
                                                INPUT_EXTENSSS_Motion_IN,
                                                PATH_INDEX_BOUNDS_IN,
                                                "Source_Animation",

                                                printEnabled
                                        );

        Animation animTarget = Animation(
                                              //MODEL
                                                INPUT_BasePath_OutPut_IN,
                                                INPUT_dynamicStringPart_IN,
                                                INPUT_EXTENSSS_Mesh_IN,
                                                INPUT_EXTENSSS_Skeleton_IN,
                                                INPUT_EXTENSSS_Skin_IN,
                                                INPUT_PATH_MODELS_INFO_IN,

                                              //ANIMATION
                                                PATH_OutputBase_IN,
                                                PATH_FolderName_INPUT_IN,
                                                INPUT_EXTENSSS_Motion_IN,
                                                PATH_INDEX_BOUNDS_IN,
                                                "Target_Animation",

                                                printEnabled
                                        );

        posedAnimations.append( animSource );
        posedAnimations.append( animTarget );

        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

        currentFrameNumber_Source = 0;
        currentFrameNumber_Target = 0;

        sequenceID_String = RadioSequenceID_String_IN;
        sequenceID        = sequenceID_String.toInt() - 1;

        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

        QFile myFile ( PATH_INDEX_BOUNDS_INNN );

        myFile.open(QIODevice::ReadOnly);

        if( !myFile.isOpen() )
        {
            qDebug() << "\n\n\n   Sequence::Sequence - ERROR, unable to open **" << PATH_INDEX_BOUNDS_INNN << "** for IndexCheat Input \n\n\n";
            return;
        }

        QTextStream myStream(&myFile);

        QString dummyDescr;
//.........这里部分代码省略.........
开发者ID:caomw,项目名称:InHandScanningICCV15_Reconstruction,代码行数:101,代码来源:sequence.cpp

示例8: QMainWindow

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    ArrayInit();

    QFile file;//загрузка jquery и добавление ноу конфликт
    file.setFileName(":/jquery-1.11.3.min.js");
    file.open(QIODevice::ReadOnly);
    jQuery = file.readAll();
    jQuery.append("\nvar qt = { 'jQuery': jQuery.noConflict(true) };");
    file.close();

    ServIP="127.0.0.1";


    QFile htmlF;//подгрузка html
    htmlF.setFileName(":/page.html");
    htmlF.open(QFile::ReadOnly);
    Html = htmlF.readAll();
    htmlF.close();

    QFile styleF;//подгрузка стилей
    styleF.setFileName("://style.qss");
    styleF.open(QFile::ReadOnly);
    QString qssStr = styleF.readAll();
    qApp->setStyleSheet(qssStr);
    styleF.close();

     QWebSettings::globalSettings()->setAttribute(QWebSettings::PluginsEnabled, true);
     QWebSettings::globalSettings()->setAttribute(QWebSettings::AutoLoadImages, true);
     QWebSettings::globalSettings()->setAttribute(QWebSettings::JavascriptEnabled, true);
     connect(ui->webView,SIGNAL(loadFinished(bool)),this,SLOT(UIloadFinished(bool)));
     ui->webView->load(QUrl("http://free-filmy.ru/"));

    connect(this,SIGNAL (phase2(QString)),this ,SLOT(Phase2Do(QString)));
    wb1=new QWebView();
    connect(wb1,SIGNAL(loadFinished(bool)),this,SLOT(loadFinished(bool)));
    connect(wb1,SIGNAL(loadProgress(int)),this, SLOT(changeProgress(int)));
    wb2=new QWebView();
    connect(wb2,SIGNAL(loadFinished(bool)),this,SLOT(loadFinished2(bool)));

    dial=new QDialog;
    wb3=new QWebView();
    pb=new QPushButton();
    pb->setText("OK");
    VBox=new QVBoxLayout;
    VBox->addWidget(wb3);
    VBox->addWidget(pb);
    HBox=new QHBoxLayout;
    HBox->addLayout(VBox);
    dial->setLayout(HBox);

    dial2=new QDialog;
    wb4=new QWebView();
    VBox2=new QVBoxLayout;
    VBox2->addWidget(wb4);
    HBox2=new QHBoxLayout;
    HBox2->addLayout(VBox2);
    dial2->setLayout(HBox2);


  connect(pb,SIGNAL(clicked(bool)),this,SLOT(pb_click(bool)));
  connect(wb3->page()->mainFrame(),SIGNAL(titleChanged(QString)),this,SLOT(img_put(QString)));

  done2=true;

}
开发者ID:ksand77,项目名称:freeclient,代码行数:69,代码来源:mainwindow.cpp

示例9: 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;
    }
// FIXME #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(QucsSettings.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:GaliumNitride,项目名称:qucs,代码行数:73,代码来源:simmessage.cpp

示例10: urlquery

void
VeloHeroUploader::requestUpload()
{
    assert(sessionId.length() > 0 );

    parent->progressLabel->setText(tr("preparing VeloHero data ..."));

    QHttpMultiPart *body = new QHttpMultiPart( QHttpMultiPart::FormDataType );

    QHttpPart textPart;
    textPart.setHeader(QNetworkRequest::ContentDispositionHeader,
    QVariant("form-data; name=\"upload_submit\""));
    textPart.setBody("hrm");
    body->append( textPart );

    QString fname = context->athlete->home->temp().absoluteFilePath(".velohero-upload.pwx" );
    QFile *uploadFile = new QFile( fname );
    uploadFile->setParent(body);

    PwxFileReader reader;
    reader.writeRideFile(context, ride->ride(), *uploadFile );
    parent->progressBar->setValue(parent->progressBar->value()+20/parent->shareSiteCount);

    int limit = 16777216; // 16MB
    if( uploadFile->size() >= limit ){
        parent->errorLabel->setText(tr("temporary file too large for upload: %1 > %1 bytes")
            .arg(uploadFile->size())
            .arg(limit) );

        eventLoop.quit();
        return;
    }

    QHttpPart filePart;
    filePart.setHeader(QNetworkRequest::ContentTypeHeader,
    QVariant("application/occtet-stream"));
    filePart.setHeader(QNetworkRequest::ContentDispositionHeader,
    QVariant("form-data; name=\"file\"; filename=\"gc-upload-velohero.pwx\""));
    uploadFile->open(QIODevice::ReadOnly);
    filePart.setBodyDevice(uploadFile);
    body->append( filePart );


    parent->progressLabel->setText(tr("sending to VeloHero..."));

    currentRequest = reqUpload;

#if QT_VERSION > 0x050000
    QUrlQuery urlquery( VELOHERO_URL + "/upload/file" );
#else
    QUrl urlquery( VELOHERO_URL + "/upload/file" );
#endif
    urlquery.addQueryItem( "view", "xml" );
    urlquery.addQueryItem( "sso", sessionId );

#if QT_VERSION > 0x050000
    QUrl url;
    url.setQuery(urlquery);
    QNetworkRequest request = QNetworkRequest(url);
#else
    QNetworkRequest request = QNetworkRequest(urlquery);
#endif

    request.setRawHeader( "Accept-Encoding", "identity" );
    request.setRawHeader( "Accept", "application/xml" );
    request.setRawHeader( "Accept-Charset", "utf-8" );

    QNetworkReply *reply = networkMgr.post( request, body );
    body->setParent( reply );

}
开发者ID:cernst72,项目名称:GoldenCheetah,代码行数:71,代码来源:VeloHeroUploader.cpp

示例11: parseASCII

bool SGFParser::parseASCII(const QString &fileName, ASCII_Import *charset, bool isFilename)
{
	QTextStream *txt = NULL;
	bool result = false;
	asciiOffsetX = asciiOffsetY = 0;
	
#if 0
	qDebug("BLACK STONE CHAR %c\n"
		"WHITE STONE CHAR %c\n"
		"STAR POINT  CHAR %c\n"
		"EMPTY POINT CHAR %c\n"
		"HOR BORDER CHAR %c\n"
		"VER BORDER CHAR %c\n",
		charset->blackStone,
		charset->whiteStone,
		charset->starPoint,
		charset->emptyPoint,
		charset->hBorder,
		charset->vBorder);
#endif
	
	if (isFilename)  // Load from file
	{
		QFile file;
		
		if (fileName.isNull() || fileName.isEmpty())
		{
			QMessageBox::warning(0, PACKAGE, Board::tr("No filename given!"));
			delete txt;
			return false;
		}
		
		file.setName(fileName);
		if (!file.exists())
		{
			QMessageBox::warning(0, PACKAGE, Board::tr("Could not find file:") + " " + fileName);
			delete txt;
			return false;
		}
		
		if (!file.open(IO_ReadOnly))
		{
			QMessageBox::warning(0, PACKAGE, Board::tr("Could not open file:") + " " + fileName);
			delete txt;
			return false;
		}
		
		txt = new QTextStream(&file);
		if (!initStream(txt))
		{
			QMessageBox::critical(0, PACKAGE, Board::tr("Invalid text encoding given. Please check preferences!"));
			delete txt;
			return false;
		}
		
		result = parseASCIIStream(txt, charset);
		file.close();
	}
	else  // a string was passed instead of a filename, copy from clipboard
	{
		if (fileName.isNull() || fileName.isEmpty())
		{
			QMessageBox::warning(0, PACKAGE, Board::tr("Importing ASCII failed. Clipboard empty?"));
			delete txt;
			return false;
		}
		
		QString buf(fileName);
		txt = new QTextStream(buf, IO_ReadOnly);
		if (!initStream(txt))
		{
			QMessageBox::critical(0, PACKAGE, Board::tr("Invalid text encoding given. Please check preferences!"));
			delete txt;
			return false;
		}
		
		result = parseASCIIStream(txt, charset);
	}
	
	delete txt;
	return result;
}
开发者ID:rd8,项目名称:qGo,代码行数:82,代码来源:sgfparser.cpp

示例12: Initializations

void ShortLocater::Initializations(){

	IPsoc->resetRelays();
	IPsoc->srcImpedanceSelection(SRC_IMP_0E);
//	IPsoc->shLocatorDetection();
    m_nADCtimer = new QTimer(this);

    IBackPlane->writeBackPlaneRegister(0x0FFF,0x001E);//clear all interrupts
    IBackPlane->writeBackPlaneRegister(0x0000,0x0020);//disable all interrupts
    IBackPlane->writeBackPlaneRegister(0x0000,0x0024);//disable global interrupt
    IBackPlane->writeBackPlaneRegister(0x0100,0x0020);//enabling psoc INT0embedded key interrupt)

    IPTKeyEvent->InvokeGPIOEvent(this,"/dev/input/event2","pt_kpp",&m_nPTKeyCode);
    IGPIOEvent->InvokeGPIOEvent(this,"/dev/input/event7","gpioevent",&m_nGPIOCode);
    IBackPlane->writeBackPlaneRegister(0x0001,0x0024);

    //        IBackPlane->writeBackPlaneRegister();
    ohms=QChar(0x2126);
    micro=QChar(0x00B5);

    //~~~~~~~~~~~~~Reading Short Values from File~~~~~~~~~~~~~~~~~~~~~~
	QStringList stringList;
	bool ok=true;
	QFile textFile;
   	textFile.setFileName("shortValuesI.txt");

    if (textFile.open(QIODevice::ReadOnly))
    {
        QTextStream textStream(&textFile);
        while (!textStream.atEnd())
        {
            stringList.append(textStream.readLine());
        }
        r200EShortValue=stringList.value(0).toDouble(&ok);
        qDebug()<<"200E Short Value:"<<r200EShortValue;
        r2EShortValue=stringList.value(1).toDouble(&ok);
        qDebug()<<"2E Short Value:"<<r2EShortValue;
       	r200mEShortValue=stringList.value(2).toDouble(&ok);
        qDebug()<<"200mE Short Value:"<<r200mEShortValue;
    }else{
        r200EShortValue=r200mEShortValue=r2EShortValue=0.0;
    }
    //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    //~~~~~~~~Check for debug panel~~~~~~~~~~~~~~~~~~~~~~~~
    QStringList debugPanel;
    QFile textFile2("debugPanel.txt");
    if (textFile2.open(QIODevice::ReadOnly))
    {
        QTextStream textStream(&textFile2);
        while (!textStream.atEnd())
        {
            debugPanel.append(textStream.readLine());
            if(debugPanel.value(0)=="1")
                ToolBox(true);
            else
                ToolBox(false);
        }
    }else{
        ToolBox(false);
    }
    //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

    IDMMLib->ApplyDACOffset(false);

    dis->setValue("OL");
    IBackPlane->writeBackPlaneRegister(0x0,0x16);
    //	Beep(false);

    AutoFlag=false;
    on_Auto_clicked();

    OffsetFlag=false;
    BuzzerFlag=false;
    msgBoxLive=false;

    ui.progressBar_2->setValue(0);
    for(int i=0;i<100;i++)
        avgRetval[i]=0.0;

    retval=retval2=retval3=0.0;
    nullify=0.0;
    nullit=0.0;
    avg=0;

    noOFsamples=1;

    rangePrevValue=33;

    ui.uE->setText(micro+ohms);

    on_r200But_clicked();
    ui.holdCap->setVisible(false);
    runFlag=true;
    startStop();

	ui.openShortEnable->setChecked(true);

	m_nAvgCount=0;
	movingAverage=5;

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

示例13: startSimulator

/*!
 * \brief SimMessage::startSimulator simulates the document in view.
 */
void SimMessage::startSimulator()
{
  // Using the Doc pointer here is risky as the user may have closed
  // the schematic, but converting the SPICE netlists is (hopefully)
  // faster than the user (I have no other idea).

  QString SimTime;
  QString Program;
  QStringList Arguments;
  QString SimPath = QDir::convertSeparators (QucsSettings.QucsHomeDir.absPath());
#ifdef __MINGW32__
  QString QucsDigiLib = "qucsdigilib.bat";
  QString QucsDigi = "qucsdigi.bat";
  QString QucsVeri = "qucsveri.bat";
#else
  QString QucsDigiLib = "qucsdigilib";
  QString QucsDigi = "qucsdigi";
  QString QucsVeri = "qucsveri";
#endif
  SimOpt = NULL;
  bool isVerilog = false;

  // Simulate text window.
  if(DocWidget->inherits("QTextEdit")) {

    TextDoc * Doc = (TextDoc*)DocWidget;

    // Take VHDL file in memory as it could contain unsaved changes.
    Stream << Doc->toPlainText();
    NetlistFile.close();
    ProgText->insert(tr("done.")+"\n");  // of "creating netlist...

    // Simulation.
    if (Doc->simulation) {
      SimTime = Doc->SimTime;
      QString libs = Doc->Libraries.lower();
      /// \todo \bug error: unrecognized command line option '-Wl'
#ifdef __MINGW32__
      if(libs.isEmpty()) {
        libs = "";
      }
      else {
        libs.replace(" ",",-l");
        libs = "-Wl,-l" + libs;
      }
#else
      if(libs.isEmpty()) {
        libs = "-c";
      }
      else {
        libs.replace(" ",",-l");
        libs = "-c,-l" + libs;
      }
#endif
      Program = pathName(QucsSettings.BinDir + QucsDigi);
      Arguments  << QucsSettings.QucsHomeDir.filePath("netlist.txt")
                 << DataSet << SimTime << pathName(SimPath)
                 << pathName(QucsSettings.BinDir) << libs;
    }
    // Module.
    else {
      QString text = Doc->toPlainText();
      VHDL_File_Info VInfo (text);
      QString entity = VInfo.EntityName.lower();
      QString lib = Doc->Library.lower();
      if (lib.isEmpty()) lib = "work";
      QString dir = QDir::convertSeparators (QucsSettings.QucsHomeDir.path());
      QDir vhdlDir(dir);
      if(!vhdlDir.exists("vhdl"))
	if(!vhdlDir.mkdir("vhdl")) {
	  ErrText->insert(tr("ERROR: Cannot create VHDL directory \"%1\"!")
			  .arg(vhdlDir.path()+"/vhdl"));
	  return;
	}
      vhdlDir.setPath(vhdlDir.path()+"/vhdl");
      if(!vhdlDir.exists(lib))
	if(!vhdlDir.mkdir(lib)) {
	  ErrText->insert(tr("ERROR: Cannot create VHDL directory \"%1\"!")
			  .arg(vhdlDir.path()+"/"+lib));
	  return;
	}
      vhdlDir.setPath(vhdlDir.path()+"/"+lib);
      QFile destFile;
      destFile.setName(vhdlDir.filePath(entity+".vhdl"));
      if(!destFile.open(QIODevice::WriteOnly)) {
	ErrText->insert(tr("ERROR: Cannot create \"%1\"!")
			.arg(destFile.name()));
	return;
      }
      destFile.writeBlock(text.ascii(), text.length());
      destFile.close();
      Program = pathName(QucsSettings.BinDir + QucsDigiLib);
      Arguments << QucsSettings.QucsHomeDir.filePath("netlist.txt")
                << pathName(SimPath)
                << entity
                << lib;
    }
//.........这里部分代码省略.........
开发者ID:GaliumNitride,项目名称:qucs,代码行数:101,代码来源:simmessage.cpp

示例14: creatNewLine

void QJDMainWindow::creatNewLine(QString lineName)
{
    QString lowerCaseLineName;
    lowerCaseLineName=lineName.toLower();
    lowerCaseLineName.simplified();
    lowerCaseLineName.remove(" ");
    qDebug()<<"creatNewLine::"<<lineName<<lowerCaseLineName;  // 所有大写阿,带空格的之类的统一小写,并且去空格

    //1. 创建文件夹,需要获取当前area文件夹名称,通过当前的名称获取
    QDir newDir;
    newDir.setPath(areaWidget->getAbsolutePath());
    if(newDir.exists(lowerCaseLineName))
    {
        QMessageBox::warning(this,"Warning!","Do not creat the same LINE again!");
        return;
    }

    if(!newDir.mkdir(lowerCaseLineName))
        qDebug()<<"Creat New Line Dir failed";

    //2. 创建.Line Desc
    QFile newDesc;
    newDesc.setFileName(newDir.path()+"/"+lowerCaseLineName+"/DescName");
    if(!newDesc.open(QFile::WriteOnly))
    {
        qDebug()<<"creat new desc open failed";
    }
    QTextStream ts(&newDesc);
    ts<<lineName<<"\n";
    newDesc.close();

    // 3. 创建Data文件夹
    QDir dataDir;
    QString dataDirPath=areaWidget->getAbsolutePath()+"/"+lowerCaseLineName;
    dataDir.setPath(dataDirPath);
    if(dataDir.exists("Data"))
    {
        QMessageBox::warning(this,"Warning!","Can not creat the Data Dir for this LINE!");
        return;
    }

    if(!dataDir.mkdir("Data"))
        qDebug()<<"Creat Line Data Dir failed";

    QFile dataDesc;
    dataDesc.setFileName(dataDir.path()+"/Data/DescName");
    if(!dataDesc.open(QFile::WriteOnly))
    {
        qDebug()<<"creat data dir desc open failed";
    }
    QTextStream datats(&dataDesc);
    datats<<"Data\n";
    dataDesc.close();

    // 4. 创建各个类型文件的文件夹
    QStringList fileTypeList=settings.value("FileType").toStringList();
    for(int i=0; i<fileTypeList.size(); i++)
    {
        QDir typeDir;
        QString typeDirPath=dataDirPath+"/Data";
        typeDir.setPath(typeDirPath);
        if(typeDir.exists(fileTypeList.at(i)))
        {
            QMessageBox::warning(this,"Warning!","Can not creat the Same Type Dir for this LINE Data!");
            return;
        }

        if(!typeDir.mkdir(fileTypeList.at(i)))
            qDebug()<<"Creat Line Data Dir failed";
    }


    setHomeDir(getHomeDir());
    areaWidget->expandToDepth(1);
}
开发者ID:xtfllbl,项目名称:Flow2,代码行数:75,代码来源:qjdmainwindow.cpp

示例15: startCrashHandler

void startCrashHandler(int signal)
{
	QFile output;
	QString lin, cmd;

	/** At the moment the backtrace function does not exists on MingW (Windows) this way
		 the code that generates the stacktrace is available only on Linux/Unix systems */
	#ifndef Q_OS_WIN
		void *stack[20];
		size_t stack_size, i;
		char **symbols=nullptr;
		stack_size = backtrace(stack, 20);
		symbols = backtrace_symbols(stack, stack_size);
	#endif

	#ifdef Q_OS_MAC
		cmd=QApplication::applicationDirPath() + GlobalAttributes::DIR_SEPARATOR +
				GlobalAttributes::CRASH_HANDLER_PATH + " -style " + GlobalAttributes::DEFAULT_QT_STYLE;
	#else
		cmd=GlobalAttributes::CRASH_HANDLER_PATH + " -style " + GlobalAttributes::DEFAULT_QT_STYLE;
	#endif

	//Creates the stacktrace file
	output.setFileName(GlobalAttributes::TEMPORARY_DIR +
										 GlobalAttributes::DIR_SEPARATOR +
										 GlobalAttributes::STACKTRACE_FILE);
	output.open(QFile::WriteOnly);

	if(output.isOpen())
	{
    lin=QString("** pgModeler crashed after receive signal: %1 **\n\nDate/Time: %2 \nVersion: %3 \nBuild: %4 \n")
        .arg(signal)
        .arg(QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss"))
        .arg(GlobalAttributes::PGMODELER_VERSION)
        .arg(GlobalAttributes::PGMODELER_BUILD_NUMBER);

		lin+=QString("Compilation Qt version: %1\nRunning Qt version: %2\n\n")
				 .arg(QT_VERSION_STR)
				 .arg(qVersion());

		output.write(lin.toStdString().c_str(), lin.size());

		#ifndef Q_OS_WIN
			for(i=0; i < stack_size; i++)
			{
				lin=QString(symbols[i]) + QString("\n");
				output.write(lin.toStdString().c_str(), lin.size());
			}
			free(symbols);
		#else
			lin=QString("** Stack trace unavailable on Windows system **");
			output.write(lin.toStdString().c_str(), lin.size());
		#endif

		output.close();
	}

	/* Changing the working dir to the main executable in order to call the crash handler
	if the PGMODELER_CHANDLER_PATH isn't set */
	QDir dir;
	dir.cd(QApplication::applicationDirPath());

	exit(1 + system(cmd.toStdString().c_str()));
}
开发者ID:Fisiu,项目名称:pgmodeler,代码行数:64,代码来源:main.cpp


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