QtQuickControls FileDialog Automation
-
I'm trying to automate picking a file in QML in a QtQuick Controls
FileDialog
. How can I invoke FileDialog's accept with a specificfileUrl
when thefileUrl
property is read only?The current attempt involves calling
filedialog.clearSelection
,filedialog.addSelection
and finallyfiledialog.accept
.clearSelection
andaddSelection
are not documented but can be found in source https://github.com/qt/qtquickcontrols/blob/dev/src/dialogs/qquickfiledialog.cpp (Assuming Qt has used a DefaultFileDialog as this can be system dependent)However
clearSelection
seems to only work sporadically, having no affect if the same FileDialog has been used manually, hence theaddSelection
fails to setfileUrl
.The following is a QML file (loaded as a basic project within QtCreator) demonstrating this. with a manual file dialog open button and an automatic one:
import QtQuick 2.9 import QtQuick 2.9 import QtQuick.Window 2.2 import QtQuick.Controls 2.4 import QtQuick.Dialogs 1.3 Window { visible: true;width: 200;height:200 FileDialog {id: filedialog; onAccepted: console.log("File Dialog Accepted: ", fileUrl, fileUrls);} Row { Button {text: "manual"; onClicked: filedialog.open()} Button { text: "auto_qml" onClicked: { console.log("Current selection:", filedialog.fileUrl, filedialog.fileUrls) filedialog.clearSelection(); console.log("cleared selection:", filedialog.fileUrl, filedialog.fileUrls) // only clears selection if manual not used let t = filedialog.addSelection("file:/home/user/tempfile.txt"); console.log("add selection success:", t) // a non existent file returns false, so file must exist filedialog.accept() } } } }