首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> C++ >> 關於C++

Qt學習之路(15):標準對話框 QFileDialog 檔案選擇器

     編輯:關於C++

QFileDialog 為檔案開啟/儲存對話框,相當於 Swing 的 JFileChooser。

靜態函式快速使用


void MainWindow::open() {
    QString path = QFileDialog::getOpenFileName(this, tr("Open Image"), ".",
        tr("Image Files(*.jpg *.png)"));
    if (path.length() == 0) {
        QMessageBox::information(NULL, tr("Path"), tr("You didn't select any files."));
    } else {
        QMessageBox::information(NULL, tr("Path"), tr("You selected ") + path);
    }
}

物件導向用法(Qt 自繪對話框)


QFileDialog *fileDialog = new QFileDialog(this);
fileDialog->setWindowTitle(tr("Open Image"));
fileDialog->setDirectory(".");
fileDialog->setFilter(tr("Image Files(*.jpg *.png)"));
if (fileDialog->exec() == QDialog::Accepted) {
    QString path = fileDialog->selectedFiles()[0];
    QMessageBox::information(NULL, tr("Path"), tr("You selected ") + path);
} else {
    QMessageBox::information(NULL, tr("Path"), tr("You didn't select any files."));
}

差異:getOpenFileName() 在 Windows/macOS 使用原生對話框;QFileDialog 物件始終使用 Qt 自繪風格。

getOpenFileName() 參數詳解

  • parent:父元件
  • caption:標題
  • dir:預設目錄(. 為執行目錄,/ 為根目錄)
  • filter:副檔名過濾(;; 分隔多組)
  • selectedFilter:預設選中過濾器
  • options:QFileDialog::Option 列舉,可 | 組合

多檔選擇用 getOpenFileNames() 回傳 QStringList。儲存對話框對應 getSaveFileName()。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved