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);
}
}
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 自繪風格。
parent:父元件caption:標題dir:預設目錄(. 為執行目錄,/ 為根目錄)filter:副檔名過濾(;; 分隔多組)selectedFilter:預設選中過濾器options:QFileDialog::Option 列舉,可 | 組合多檔選擇用 getOpenFileNames() 回傳 QStringList。儲存對話框對應 getSaveFileName()。