1. 程式人生 > 其它 >QT 6.2 QML 的 FileDialog 元件

QT 6.2 QML 的 FileDialog 元件

使用環境

  • Qt 6.2.2 MingGW 64-bit
  • Windows 10
  • Qt Creator

引數 (下面的引數連結到了 QT官方)

程式碼實現

import QtQuick 2.15
import QtQuick.Window 2.15
import QtQuick.Controls 2.15
// 此處不能新增版本號 
// https://doc.qt.io/qt-6/qml-qtquick-dialogs-filedialog.html
import QtQuick.Dialogs

Window {
    width: 400
    height: 100
    visible: true
    title: qsTr("FileDialogTest")

    Column {
        anchors.fill: parent
        spacing: 3

        Button {
            id: fileSelectButton
            text: "選擇檔案"
            onClicked: {
                fileSelect.open()
            }
        }
        Label {
            id: filePath
        }

        Label {
            id: fileNames
        }
    }

    FileDialog {
        id: fileSelect
        title: "請選擇檔案"
        // 檔案型別過濾器
        nameFilters: ["All Files (*.*)"]
        // 修改確認按鈕名稱
        acceptLabel: "好"
        // 儲存對話方塊中當前選定的檔案
        currentFile: "請先選擇檔案。。。。"
        // 對話方塊模式 OpenFile OpenFiles SaveFile
        fileMode: FileDialog.OpenFile
				// 確認之後的回撥
        onAccepted: {
            // 獲取檔名稱
            let fileName = fileSelect.currentFile.toString().substring(
                    fileSelect.currentFolder.toString().length + 1)
            filePath.text = "路徑【" + fileSelect.currentFolder + "】"
            // 獲取檔案路徑
            fileNames.text = "名稱【" + fileName + "】"
        }
        // 取消回撥
        onRejected: {
            console.log("Canceled")
        }
    }
}

執行例項

歡迎前往我的個人部落格 www.runbrick.com,部落格園同步更新。