我在 QML 中有一个 FileDialog。 如果单击按钮,对话框将打开,我可以通过“文件对话框”窗口选择文件。 我想在单击“文件对话框”部分之外时自动关闭“文件对话框”。 我在网上搜索了很多,但找不到任何解决我的问题的方法。 我正在使用 Qt 6.2
Item {
id: root
width: 1920
height: 1080
Rectangle {
id: main
anchors.fill: parent
color: "#050616"
GridLayout {
id: grid
anchors.fill: parent
columns: 2
rows: 2
Rectangle {
id:addApplyFile
Layout.preferredWidth: 537
Layout.preferredHeight: 64
border.color: "#0081d1"
border.width: 1
color: "transparent"
Button {
id:addFileBtn
width: 130
height: 36
background: Rectangle {
border.color: "#FFBD03"
color: "#050616"
radius: 3
}
Text {
id: addFileText
color: "#FFFFFF"
text: "AddFile"
}
Image {
width: 24
height: 24
source: "qrc:/QMLItemsLib/Icons/addFile.png"
}
onClicked: {
fileDialog.folder = "file://"+ env.env_HOME +"/Common/"
fileDialog.open()
}
}
FileDialog {
id: fileDialog
modality: Qt.NonModal
title: "Please choose a file"
property int fileIndex: -1 // Custom property to store the file index
onAccepted: {
var filePath = fileDialog.file;
if (fileIndex < 0) {
// Add a new file to the list
fileListModel.addFile(filePath, fileListModel.rowCount())
} else {
// Update an existing file in the list
fileListModel.updateFile(filePath, fileIndex)
}
fileIndex = -1
}
}
}
}
任何人都可以帮我解决这个问题吗???!!!
我同意@Jürgen Lutz 的观点。如果默认的
FileDialog
没有给你你想要的,那么你就必须自己动手。看来你的要求很具体。这推动我们走向定制组件。作为起点,请考虑在 FolderListModel
中使用 Popup
。
Page {
Popup {
id: filePopup
signal accepted(fileName: string)
anchors.centerIn: parent
width: parent.width / 2
height: parent.height / 2
ListView {
anchors.fill: parent
model: FolderListModel { }
delegate: Button {
text: fileName
onClicked: { filePopup.accepted(fileName); Qt.callLater(filePopup.close) }
}
}
footer: Button {
text: "File Dialog"
onClicked: filePopup.open()
}
}
但是,当您开始沿着这条道路走下去时,您将承担管理和维护组件的重担,并且可能还要承担一系列无休止的用户需求。这应该会让您重新思考在这里花费的时间是否值得,而不是花在管理用户期望和接受开箱即用的
FileDialog
功能上的时间。
参考资料: