DiagramDesigner/PropertyEditor/resources/Qml/ValueEditor/FileSelector.qml

101 lines
2.6 KiB
QML

import QtQuick
import QtQuick.Controls
import QtQuick.Dialogs
import QtQuick.Layouts
import QtCore
import ColorPalette
Item {
id: control
// 属性接口
property var value
property string fileFilter: "所有文件 (*.*)" // 文件过滤器
property bool selectMultiple: false // 是否多选
implicitHeight: fileBox.implicitHeight
signal asValueChanged(text: var)
function setValue(newValue: var) {
if (newValue !== value) {
value = newValue
fileBox.value = value
asValueChanged(value)
}
}
LineTextBox {
id: fileBox
value: control.value
anchors.left: parent.left
anchors.right: button.left
anchors.verticalCenter: parent.verticalCenter
onValueChanged: {
control.setValue(value)
}
}
Button {
id: button
anchors.right: parent.right
anchors.verticalCenter: parent.verticalCenter
width: 30
height: 25
text: "..."
palette.buttonText: ColorPalette.theme.textPrimary
background: Rectangle {
color: ColorPalette.theme.buttonBackground
}
onClicked: {
fileDialog.open()
}
}
FileDialog {
id: fileDialog
title: control.selectMultiple ? "选择多个文件" : "选择文件"
fileMode: control.selectMultiple ? FileDialog.OpenFiles : FileDialog.OpenFile
// 设置文件过滤器
nameFilters: {
if (control.fileFilter) {
return control.fileFilter.split(";;")
}
return ["所有文件 (*.*)"]
}
onAccepted: {
if (control.selectMultiple) {
// 多选模式
var filePaths = []
for (var i = 0; i < selectedFiles.length; i++) {
var filePath = selectedFiles[i].toString()
filePath = removeFileProtocol(filePath)
filePaths.push(filePath)
}
// 多个文件用分号分隔
control.setValue(filePaths.join(";"))
} else {
// 单选模式
var filePath = selectedFile.toString()
filePath = removeFileProtocol(filePath)
control.setValue(filePath)
}
}
}
// 辅助函数:移除文件协议前缀
function removeFileProtocol(path) {
if (path.startsWith("file:///")) {
return path.substring(8)
} else if (path.startsWith("file://")) {
return path.substring(7)
}
return path
}
}