如何在Ubuntu手機上實現一個FileDialog,ubuntufiledialog
前一段時間,有個開發人員問我能否在Ubuntu手機中使用QtQuick.Dialogs來實現FileDialog。目前在手機上沒有Qt這個庫的實現。最主要的原因是它不使用unit grid的方式來布局,所以在真的手機上顯得非常小。那麼我們怎麼才能實現同樣的功能呢?
我們首先來查看一下我們的Ubuntu Qt所提供的API Dialog。這裡我們有提供一個Dialog的control.我們可以仿照上面的常式來寫出我們所需要的常式。另外,我們也需要使用另外一個API FolderListModel。通過這個API我們可以得到我們所需要的檔案的目錄的所有的檔案:
通過對這兩個API的瞭解和和使用,我們可以很快的做出如下的測試應用:
import QtQuick 2.0import Ubuntu.Components 1.1import Ubuntu.Components.Popups 0.1import Qt.labs.folderlistmodel 2.1/*! \brief MainView with a Label and Button elements.*/MainView { // objectName for functional testing purposes (autopilot-qt5) objectName: "mainView" // Note! applicationName needs to match the "name" field of the click manifest applicationName: "filedialog.ubuntu" /* This property enables the application to change orientation when the device is rotated. The default is false. */ //automaticOrientation: true // Removes the old toolbar and enables new features of the new header. useDeprecatedToolbar: false width: units.gu(60) height: units.gu(75) Page { title: i18n.tr("Simple") Button { id: launcher text: i18n.tr("Open") width: units.gu(16) onClicked: PopupUtils.open(dialog, null) } Component { id: dialog Dialog { id: dialogue title: "FileList Dialog" text: "Show the files" ListView { id: listview width: parent.width height: 200 FolderListModel { id: folderModel nameFilters: ["*.qml"] } Component { id: fileDelegate Text { id: text text: fileName MouseArea { anchors.fill: parent onClicked: { console.log("it is clicked"); listview.currentIndex = index; } } } } // Define a highlight with customized movement between items. Component { id: highlightBar Rectangle { width: fileDelegate.width; height: 50 color: "red" y: listview.currentItem.y; Behavior on y { SpringAnimation { spring: 2; damping: 0.1 } } } } focus: true model: folderModel delegate: fileDelegate highlight: highlightBar } Row { id: row width: parent.width spacing: units.gu(1) Button { width: parent.width/2 text: "Cancel" onClicked: PopupUtils.close(dialogue) } Button { width: parent.width/2 text: "Confirm" color: UbuntuColors.green onClicked: { console.log("caller: " + dialogue.caller); console.log("currentIndex: " + listview.currentIndex); console.log(folderModel.get(listview.currentIndex, "fileName")); launcher.update(); PopupUtils.close(dialogue) } } } } } }}
運行我們的應用,我們可以看到:
這裡必須指出的是FolderListModel並不是可以訪問系統的任何一個目錄的。我們可以參考文章“Ubuntu OS應用Runtime Enviroment”來得到哪些目錄是可以訪問的。對訪問另外一個應用所擁有的檔案來說,我們可以通過使用contenthub來訪問。
所有應用的源碼在:git clone https://gitcafe.com/ubuntu/filedialog.git