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


C++ QFileDialog类代码示例

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


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

示例1: QFileDialog

/**
 * Shows a dialog for choosing a file name. Saving the file is up to
 * the caller.
 *
 * @param type Will contain the file type that was chosen by the user.
 *             Can be NULL to be ignored.
 *
 * @return File name with path and extension to determine the file type
 *         or an empty string if the dialog was cancelled.
 */
QString QG_FileDialog::getSaveFileName(QWidget* parent, RS2::FormatType* type) {
    // read default settings:
    RS_SETTINGS->beginGroup("/Paths");
    QString defDir = RS_SETTINGS->readEntry("/Save",
                                              RS_SYSTEM->getHomeDir());
    QString defFilter = RS_SETTINGS->readEntry("/SaveFilter",
                                                 "Drawing Exchange DXF 2000 (*.dxf)");
    //QString defFilter = "Drawing Exchange (*.dxf)";
    RS_SETTINGS->endGroup();

    // prepare file save as dialog:
    QFileDialog* fileDlg = new QFileDialog(parent,"Save as");
    QStringList filters;
    bool done = false;
    bool cancel = false;
    QString fn = "";

    filters.append("Drawing Exchange DXF 2000 (*.dxf)");
#ifdef USE_DXFRW
    filters.append("New Drawing Exchange DXF 2000 (*.DXF)");
#endif
    filters.append("Drawing Exchange DXF R12 (*.dxf)");
    filters.append("LFF Font (*.lff)");
    filters.append("Font (*.cxf)");
    filters.append("JWW (*.jww)");

    fileDlg->setFilters(filters);
    fileDlg->setFileMode(QFileDialog::AnyFile);
    fileDlg->setWindowTitle(QObject::tr("Save Drawing As"));
    fileDlg->setDirectory(defDir);
    fileDlg->setAcceptMode(QFileDialog::AcceptSave);
    fileDlg->selectFilter(defFilter);

    // run dialog:
    do {
        // accepted:
        if (fileDlg->exec()==QDialog::Accepted) {
            QStringList fl = fileDlg->selectedFiles();
            if (!fl.isEmpty())
                fn = fl[0];
            fn = QDir::convertSeparators( QFileInfo(fn).absoluteFilePath() );
            cancel = false;

            // append default extension:
            // TODO, since we are starting to suppor tmore extensions, we need to find a better way to add the default
            if (QFileInfo(fn).fileName().indexOf('.')==-1) {
                if (fileDlg->selectedFilter()=="LFF Font (*.lff)") {
                    fn+=".lff";
                } else if (fileDlg->selectedFilter()=="Font (*.cxf)") {
                        fn+=".cxf";
                } else {
                    fn+=".dxf";
                }
            }

            // set format:
            if (type!=NULL) {
                if (fileDlg->selectedFilter()=="LFF Font (*.lff)") {
                    *type = RS2::FormatLFF;
                } else if (fileDlg->selectedFilter()=="Font (*.cxf)") {
                    *type = RS2::FormatCXF;
                } else if (fileDlg->selectedFilter()=="Drawing Exchange DXF R12 (*.dxf)") {
                    *type = RS2::FormatDXF12;
#ifdef USE_DXFRW
#if QT_VERSION >= 0x040400
                } else if (fileDlg->selectedNameFilter()=="New Drawing Exchange DXF 2000 (*.DXF)") {
                    *type = RS2::FormatDXFRW;
#endif // QT_VERSION
#endif // USE_DXFFRW
                } else if (fileDlg->selectedFilter()=="JWW (*.jww)") {
                    *type = RS2::FormatJWW;
                } else {
                    *type = RS2::FormatDXF;
                }
            }

#if !defined (_WIN32) && !defined (__APPLE__)
            // overwrite warning:
            if(QFileInfo(fn).exists()) {
                int choice =
                        QMessageBox::warning(parent, QObject::tr("Save Drawing As"),
                                             QObject::tr("%1 already exists.\n"
                                                         "Do you want to replace it?")
                                             .arg(fn),
                                             QMessageBox::Yes | QMessageBox::No | QMessageBox::Cancel,QMessageBox::Cancel);

                switch (choice) {
                case QMessageBox::Yes:
                    done = true;
                    break;
//.........这里部分代码省略.........
开发者ID:isili,项目名称:LibreCAD,代码行数:101,代码来源:qg_filedialog.cpp

示例2: QWidget

void ContentViewer::addHTMLTab()
{
  if(_entity->hasHTML())
  {
    QWidget *tab=new QWidget(ui->tvFormats);
    tab->setObjectName("HTML");
    tab->setWindowTitle("HTML");

    QVBoxLayout *tabLayout=new QVBoxLayout();

    QTabWidget *innerTabWidget=new QTabWidget(tab);
    QWidget *previewTab=new QWidget(innerTabWidget);
    previewTab->setObjectName("preview");
    previewTab->setWindowTitle("preview");

    QVBoxLayout *previewTabLayout=new QVBoxLayout();


    QTextBrowser *previewTextBorowser=new QTextBrowser(tab);
    previewTextBorowser->setText(_entity->HTMLText(false,-1));
    previewTextBorowser->setReadOnly(true);

    QHBoxLayout *previewTabOptionsLayout=new QHBoxLayout();
    previewTabOptionsLayout->addStretch();

    QLabel *previewCBLabel=new QLabel(previewTab);
    previewCBLabel->setText("background color : ");
    previewTabOptionsLayout->addWidget(previewCBLabel);

    QPushButton *previewBCButton=new QPushButton(previewTab);
    previewBCButton->setText("white");
    previewBCButton->setStyleSheet("background-color : white ;");
    connect(previewBCButton,&QPushButton::clicked,this,[this,previewTextBorowser,previewBCButton](){
      QColorDialog CD(this);
      if(CD.exec())
      {
        QColor color=CD.selectedColor();
        previewTextBorowser->setStyleSheet("background-color :  "+color.name()+";");
        previewBCButton->setText(color.name());
        previewBCButton->setStyleSheet("background-color :  "+color.name()+";");
      }
    });

    previewTabOptionsLayout->addWidget(previewBCButton);
    previewTabLayout->addLayout(previewTabOptionsLayout);

    previewTabLayout->addWidget(previewTextBorowser);
    previewTab->setLayout(previewTabLayout);
    innerTabWidget->addTab(previewTab,"preview");

    QWidget *codeTab=new QWidget(innerTabWidget);
    codeTab->setObjectName("code");
    codeTab->setWindowTitle("code");

    QVBoxLayout *codeTabLayout=new QVBoxLayout();
    QPlainTextEdit *codeTextEdit=new QPlainTextEdit(codeTab);
    codeTextEdit->setPlainText(_entity->HTMLText(false,-1));
    codeTextEdit->setReadOnly(true);
    codeTabLayout->addWidget(codeTextEdit);

    codeTab->setLayout(codeTabLayout);

    innerTabWidget->addTab(codeTab,"code");


    tabLayout->addWidget(innerTabWidget);

    QHBoxLayout *infoLayout=new QHBoxLayout();
    QLabel *infoLabel=new QLabel(tab);
    infoLabel->setText(QString("<b>length :</b> %1").arg(previewTextBorowser->toPlainText().count())
                               +"  "+QString("<b>size :</b> %1 KB").arg((double)_entity->formatSize("text/html")/1024));
    infoLayout->addWidget(infoLabel);

    QPushButton *btnExport=new QPushButton(tab);
    connect(btnExport,&QPushButton::clicked,this,[this](){
      QFileDialog dialog;
      dialog.setAcceptMode(QFileDialog::AcceptSave);
      dialog.setWindowTitle("select a file to save HTML");
      dialog.setWindowIcon(QIcon(Resources::Export16));
      dialog.setFileMode(QFileDialog::AnyFile);
      dialog.setDefaultSuffix("html");
      for(;;)
      {
        if(dialog.exec())
        {
          int length=dialog.selectedFiles().length();
          if(length>0 && length==1)
          {
            QFile file(dialog.selectedFiles().at(0));
            file.open(QIODevice::WriteOnly);
            if(file.isWritable())
            {
              qint64 i= file.write(this->_entity->HTMLText(false,-1).toUtf8());
              if(i<0)
              {
                int messageResult= QMessageBox::critical(this,"cannot write to the file.","cannot write to the selected file.nothing saved. \ntry another file.",QMessageBox::Ok,QMessageBox::Cancel);
                if(messageResult==QMessageBox::Ok)
                  continue;
                else break;
              }
//.........这里部分代码省略.........
开发者ID:Reemjd,项目名称:genius,代码行数:101,代码来源:contentviewer.cpp

示例3: return

void DaoWorker::loadModelIntoAYDesigner(const std::string fileDownloaded)
{
    if(boost::filesystem::exists(fileDownloaded))
    {
        std::string suffix = boost::filesystem::extension(fileDownloaded);
        if(suffix == ".stl" || suffix == ".STL")
        {
            LoggerManager::instance()->logInfo("AY Designer is about to run, loading "+fileDownloaded+".");
            std::string filePathTemp = fileDownloaded;
            std::replace_if(filePathTemp.begin(), filePathTemp.end(), [] (char c) { return (c == '/'); }, '\\\\');

            std::string formatedAyDesignerUrl = MainWindow::GetMainWindow()->getAyDesignerPath();
            if(!boost::filesystem::exists(formatedAyDesignerUrl))
            {
                QFileDialog dialog;
                dialog.setNameFilter(trUtf8("AY Designer (*.exe)"));

                if (dialog.exec())
                {
                    std::string path = QString::fromUtf8(dialog.selectedFiles()[0].toUtf8().constData()).toStdString();
                    MainWindow::GetMainWindow()->updateAyDesignerPathForSetting(path);
                    formatedAyDesignerUrl = MainWindow::GetMainWindow()->getAyDesignerPath();
                }
                else
                {
                    LoggerManager::instance()->logInfo("update AyDesignerPath for setting cancelled.");
                    return;
                }
            }
            QString program = QString::fromStdString(formatedAyDesignerUrl);
            QStringList args;
            args.push_back("-s");
            args.push_back(QString::fromStdString(filePathTemp));

            QProcess::execute(program, args);

            //AYDesigner processes this file, save it to override the original file, "save and save as... in aydesigner"
            //...

            LoggerManager::instance()->logInfo("AY Designer is closed.");
        }
        else if(suffix == ".ply" || suffix == ".PLY")
        {
            LoggerManager::instance()->logInfo("AY Designer is about to run, loading "+fileDownloaded+".");
            std::string filePathTemp = fileDownloaded;
            std::replace_if(filePathTemp.begin(), filePathTemp.end(), [] (char c) { return (c == '/'); }, '\\\\');

            std::string formatedAyDesignerUrl = MainWindow::GetMainWindow()->getAyDesignerPath();
            if(!boost::filesystem::exists(formatedAyDesignerUrl))
            {
                QFileDialog dialog;
                dialog.setNameFilter(trUtf8("AY Designer (*.exe)"));

                if (dialog.exec())
                {
                    std::string path = QString::fromUtf8(dialog.selectedFiles()[0].toUtf8().constData()).toStdString();
                    MainWindow::GetMainWindow()->updateAyDesignerPathForSetting(path);
                    formatedAyDesignerUrl = MainWindow::GetMainWindow()->getAyDesignerPath();
                }
                else
                {
                    LoggerManager::instance()->logInfo("update AyDesignerPath for setting cancelled.");
                    return;
                }
            }
            QString program = QString::fromStdString(formatedAyDesignerUrl);
            QStringList args;
            args.push_back("-p");
            args.push_back(QString::fromStdString(filePathTemp));

            QProcess::execute(program, args);

            //AYDesigner processes this file, save it to override the original file, "save and save as... in aydesigner"
            //...

            LoggerManager::instance()->logInfo("AY Designer is closed.");
        }
        else
            LoggerManager::instance()->logInfo("unsupported cloud file format for AYDesigner.");
    }
}
开发者ID:conna,项目名称:AYExplorer,代码行数:81,代码来源:daoworker.cpp

示例4: QFileDialog

//////////////////////////////////////////////////////////////////////////////////
// This function is called when progress needs to be loaded from a text file.
//////////////////////////////////////////////////////////////////////////////////
void MainController::onLoadProgress() {

    if(test) testfile << "MC7  ####################### MainController onLoadProgress #######################\n";

    QString filePath;
    QFileDialog* fileDialog = new QFileDialog(&view, "Load Progress", "", "*.*");
    if(fileDialog->exec()) filePath = fileDialog->selectedFiles().first();
    if(filePath != "")
    {
        if(test) testfile << "MC8  FilePath is not empty\n";
        if(puzzle != NULL){
            if(test) testfile << "MC36 Puzzle is not NULL\n";
            //User started game, do they want to save progress?
            QMessageBox msgBox;
            msgBox.setText("You have unsaved progress.");
            msgBox.setInformativeText("Do you want to save your progress?");
            msgBox.setStandardButtons(QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel);
            msgBox.setDefaultButton(QMessageBox::Save);
            int ret = msgBox.exec();

            if(ret == msgBox.Save){
                if(test) testfile << "MC37 MessageBox save button clicked\n";
                //Save user progress
                onSaveProgress();
            }
            else if(ret == msgBox.Discard){
                if(test) testfile << "MC38 MessageBox discard button clicked\n";
                //Discard user progress
                //Do nothing
            }
            else if(ret == msgBox.Cancel){
                if(test) testfile << "MC39 MessageBox cancel button clicked\n";
                //Don't save or discard progress
                return;
            }

            //User done saving/discarding game, clear board and delete puzzle
            view.clearBoard();
            delete puzzle;
        }

        puzzle = currentProgressSerializer.deserialize(filePath, puzzleSerializer);

        //Display the default and current board
        enableUndoRedo = false;
        displayDefaultBoard();
        displayCurrentBoard();
        enableUndoRedo = true;

        if(puzzle->undo.count() > 0){
            if(test) testfile << "MC9  Puzzle undo count > 0\n";
            view.clearAction->setEnabled(true);
            view.undoAction->setEnabled(true);
        }
        if(puzzle->redo.count() > 0){
            if(test) testfile << "MC10 Puzzle redo count > 0\n";
            view.redoAction->setEnabled(true);
        }

        view.centralWidget()->setEnabled(true);
    } 
    else{
        if(test) testfile << "MC11 Filepath was empty\n";
        //Popup error message...
        //TODO
    }
}
开发者ID:NickABoen,项目名称:Sudoku,代码行数:70,代码来源:MainController.cpp

示例5: defined


//.........这里部分代码省略.........
        QString mFilters;
        QString mCaption;
    };

    if (aSelectedFilter)
        *aSelectedFilter = QString::null;

    /* Local event loop to run while waiting for the result from another
     * thread */
    QEventLoop loop;

    QString startWith = QDir::toNativeSeparators (aStartWith);
    LoopObject loopObject ((QEvent::Type) GetOpenFileNameEvent::TypeId, loop);

    if (aParent)
        aParent->setWindowModality (Qt::WindowModal);

    Thread openDirThread (aParent, &loopObject, startWith, aFilters, aCaption);
    openDirThread.start();
    loop.exec();
    openDirThread.wait();

    if (aParent)
        aParent->setWindowModality (Qt::NonModal);

    return QStringList() << loopObject.result();

#elif defined (VBOX_WS_X11) && (QT_VERSION < 0x040400)

    /* Here is workaround for Qt4.3 bug with QFileDialog which crushes when
     * gets initial path as hidden directory if no hidden files are shown.
     * See http://trolltech.com/developer/task-tracker/index_html?method=entry&id=193483
     * for details */
    QFileDialog dlg (aParent);
    dlg.setWindowTitle (aCaption);
    dlg.setDirectory (aStartWith);
    dlg.setFilter (aFilters);
    if (aSingleFile)
        dlg.setFileMode (QFileDialog::ExistingFile);
    else
        dlg.setFileMode (QFileDialog::ExistingFiles);
    if (aSelectedFilter)
        dlg.selectFilter (*aSelectedFilter);
    dlg.setResolveSymlinks (aResolveSymlinks);
    QAction *hidden = dlg.findChild <QAction*> ("qt_show_hidden_action");
    if (hidden)
    {
        hidden->trigger();
        hidden->setVisible (false);
    }
    return dlg.exec() == QDialog::Accepted ? dlg.selectedFiles() : QStringList() << QString::null;

#elif defined (VBOX_WS_MAC) && (QT_VERSION >= 0x040600) && (QT_VERSION < 0x050000)

    /* After 4.5 exec ignores the Qt::Sheet flag.
     * See "New Ways of Using Dialogs" in http://doc.trolltech.com/qq/QtQuarterly30.pdf why.
     * We want the old behavior for file-save dialog. Unfortunately there is a bug in Qt 4.5.x
     * which result in showing the native & the Qt dialog at the same time. */
    QFileDialog dlg(aParent);
    dlg.setWindowTitle(aCaption);

    /* Some predictive algorithm which seems missed in native code. */
    QDir dir(aStartWith);
    while (!dir.isRoot() && !dir.exists())
        dir = QDir(QFileInfo(dir.absolutePath()).absolutePath());
    const QString strDirectory = dir.absolutePath();
开发者ID:miguelinux,项目名称:vbox,代码行数:67,代码来源:QIFileDialog.cpp

示例6: downloadImageAction

void NWebView::downloadRequested(QNetworkRequest req) {
    QString urlString = req.url().toString();
    if (urlString == "")  {
        downloadImageAction()->trigger();
        return;
    }
    if (urlString.startsWith("nnres:")) {
        int pos = urlString.indexOf(global.attachmentNameDelimeter);
        QString extension = "";
        if (pos > 0) {
            extension = urlString.mid(pos+global.attachmentNameDelimeter.length());
            urlString = urlString.mid(0,pos);
        }
        urlString = urlString.mid(6);

        qint32 lid = urlString.toInt();
        ResourceTable resTable(global.db);
        Resource r;
        resTable.get(r, lid, false);
        QString filename;
        ResourceAttributes attributes;
        if (r.attributes.isSet())
            attributes = r.attributes;
        if (attributes.fileName.isSet())
            filename = attributes.fileName;
        else
            filename = urlString + QString(".") + extension;

        QFileDialog fd;
        fd.setFileMode(QFileDialog::AnyFile);
        fd.setWindowTitle(tr("Save File"));
        fd.setAcceptMode(QFileDialog::AcceptSave);
        fd.selectFile(filename);
        fd.setConfirmOverwrite(true);
        if (fd.exec()) {
            if (fd.selectedFiles().size() == 0)
                return;
            filename = fd.selectedFiles()[0];
            QFile newFile(filename);
            newFile.open(QIODevice::WriteOnly);
            Data d;
            if (r.data.isSet())
                d = r.data;
            QByteArray body;
            if (d.body.isSet())
                body = d.body;
            int size = 0;
            if (d.size.isSet())
                size = d.size;
            newFile.write(body, size);
            newFile.close();
            return;
        }
    }
    if (urlString.startsWith("file:////")) {
        if (!req.url().isValid())
            return;
        urlString = urlString.mid(8);
        QFileDialog fd;
        fd.setFileMode(QFileDialog::AnyFile);
        fd.setWindowTitle(tr("Save File"));
        fd.setAcceptMode(QFileDialog::AcceptSave);
        QString oldname = urlString;
        fd.selectFile(urlString.replace(global.fileManager.getDbaDirPath(), ""));
        fd.setConfirmOverwrite(true);
        if (fd.exec()) {
            if (fd.selectedFiles().size() == 0)
                return;
            QString newname = fd.selectedFiles()[0];
            QFile::remove(urlString);
            QFile::copy(oldname, newname);
            return;
        }

    }
}
开发者ID:Hexcles,项目名称:Nixnote2,代码行数:76,代码来源:nwebview.cpp


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