Помощь - Поиск - Пользователи - Календарь
Полная версия этой страницы: QML TableView. Обработка данных и область видимости
Форум на CrossPlatform.RU > Библиотеки > Qt > Qt Quick
resager
Очень давно писал на Qt и начал знакомиться с QML, сейчас снова начал, но многие моменты не понимаю.

Не могу найти решение нескольких вопросов, поэтому прошу помощи.

1) почему пишет "qrc:/main.qml:294: ReferenceError: folderModel is not defined". Попытка обратиться к элементу с указанным ID происходит из FileDialog, который не имеет родителя, а элемент с указанным ID имеет много родителей. Таких моментов много, не могу понять, как обращаться к таким элементов и какая здесь преграда.

2) Есть TableView, в него необходимо добавить список файлов из папки (выбранной с помощью FileDialog). Причем необходимо получить сначала список файлов, а затем помимо информации, которую предоставляет FolderListModel получить ещё и расширение картинки (если это картинка) и ещё в один столбец произвольную строку.

Никак не пойму, как это сделать и через какие прослойки.

Собственно как вообще можно в JS в Qt получить список файлов и совершить с ним какие-либо манипуляции, а затем добавить строки в таблицу? Во всех примерах как-то совсем непрозрачно строится модель и автоматом данные отображаются. (для таблицы даже делегата не нужно указывать, судя по примерам).

Вот мой ужасный код:
Раскрывающийся текст


import QtQuick 2.4
import QtQuick.Controls 1.3
import QtQuick.Window 2.2
import QtQuick.Dialogs 1.2
import Qt.labs.folderlistmodel 2.1
import QtQuick.Layouts 1.1
//import org.qtproject.example 1.0

ApplicationWindow {
    title: qsTr("Сортировка изображений по категориям/папкам")
    width: 640
    height: 480
    visible: true

    menuBar: MenuBar {
        Menu {
            title: qsTr("&File")
            MenuItem {
                text: qsTr("&Open")
                onTriggered: fileDialog.open();
/*
                onTriggered: {
                    listModel.append({
                                  title: "some value",
                                  author: "Another value"
                              });
                }*/
                    //messageDialog.show(qsTr("Open action triggered"));
            }
            MenuItem {
                text: qsTr("E&xit")
                onTriggered: Qt.quit();
            }
        }
    }


    MainForm {
        anchors.fill: parent
        id: mainForm

        TabView {
            anchors.fill: parent
            id: tabView

            Tab {
                title: "Images sort"
                id: tabImageSort

                SplitView {
                    anchors.fill: parent
                    orientation: Qt.Horizontal
                    id: splitView

                    Button {
                        text: "Add row"
                        x:20
                        y:130
                        onClicked: {
                            /*listModel.append({
                                                 fileid: "1",
                                                 filename: "FFDGM424fWFJERW43242.png",
                                                 filesize: "1324",
                                                 fileextension: "PNG",
                                                 imageheight: "400",
                                                 imagewidth: "600",
                                                 filecategory: "Unsorted"
                                             });*/
                        }
                    }

                    TableView {
                        id: tableView

                        frameVisible: false
                        sortIndicatorVisible: true

                        //anchors.fill: parent

                        Layout.minimumWidth: 400
                        Layout.minimumHeight: 240
                        Layout.preferredWidth: 600
                        Layout.preferredHeight: 400

                        TableViewColumn {
                            id: idColumn
                            title: "ID"
                            role: "fileid"
                            movable: false
                            resizable: true
                            //width: tableView.viewport.width - authorColumn.width
                        }

                        TableViewColumn {
                            id: nameColumn
                            title: "Name"
                            role: "filename"
                            movable: false
                            resizable: true
                            width: tableView.viewport.width / 3
                        }

                        TableViewColumn {
                            id: sizeColumn
                            title: "Size"
                            role: "filesize"
                            movable: false
                            resizable: true
                            //width: tableView.viewport.width / 8
                        }

                        TableViewColumn {
                            id: typeColumn
                            title: "Type"
                            role: "fileextension"
                            movable: false
                            resizable: true
                            //width: tableView.viewport.width / 8
                        }

                        TableViewColumn {
                            id: heightColumn
                            title: "Height"
                            role: "imageheight"
                            movable: false
                            resizable: true
                            //width: tableView.viewport.width / 8
                        }

                        TableViewColumn {
                            id: widthColumn
                            title: "Width"
                            role: "imagewidth"
                            movable: false
                            resizable: true
                            //width: tableView.viewport.width / 8
                        }

                        TableViewColumn {
                            id: catColumn
                            title: "Category"
                            role: "filecategory"
                            movable: false
                            resizable: true
                            //width: tableView.viewport.width / 8
                        }

                        FolderListModel {
                            id: folderModel
                            //folder: 'D:\RUDB\pictures\social'
                            nameFilters: ["*.*"]
                        }

                        itemDelegate: Item {
                            Text {
                                anchors.left: parent.left
                                anchors.verticalCenter: parent.verticalCenter
                                renderType: Text.NativeRendering
                                text: styleData.value
                            }
                        }

                        /*
                        Component {
                            id: fileDelegate
                            Text { text: fileName }
                        }*/

                        model: folderModel
/*

                        ListModel{
                            id: listModel
                        }

                        model: listModel
*/
                       /*
                        itemDelegate: Item {
                            Text {
                                anchors.verticalCenter: parent.verticalCenter
            //                        color: "blue"
            //                        if (enabledCheck.checked = false)
            //                        color: "gray"
                                enabled: enabledCheck.checked
                                elide: styleData.elideMode
                                text: styleData.value
                            } // text
                        } // Item

                        */


                        /*
                        itemDelegate: Item {
                            Text {
                                anchors.verticalCenter: parent.verticalCenter
                                color: styleData.textColor
                                elide: styleData.elideMode
                                text: styleData.value
                            }
                        }*/

/*
                        model: SortFilterProxyModel {
                            id: proxyModel
                            source: sourceModel.count > 0 ? sourceModel : null

                            sortOrder: tableView.sortIndicatorOrder
                            sortCaseSensitivity: Qt.CaseInsensitive
                            sortRole: sourceModel.count > 0 ? tableView.getColumn(tableView.sortIndicatorColumn).role : ""

                            filterString: "*" + searchBox.text + "*"
                            filterSyntax: SortFilterProxyModel.Wildcard
                            filterCaseSensitivity: Qt.CaseInsensitive
                        }*/

                        //model: folderModel
/*
                        FolderListModel {
                                id: folderModel
                                nameFilters: ["*.*"]
                            }*/
/*
                        ListModel {
                            id: sourceModel
                            ListElement {
                                title: "Moby-Dick"
                                author: "Herman Melville"
                            }
                            ListElement {
                                title: "The Adventures of Tom Sawyer"
                                author: "Mark Twain"
                            }
                            ListElement {
                                title: "РУсский текст 333"
                                author: "какая кодирвока 444"
                            }
                        }*/
                    } // TableView
                    Rectangle {
                        id: imageFrame
                        Layout.minimumWidth: 200
                        Layout.minimumHeight: 200
                    } //imageFrame

                    ListView {
                        id: categoryList
                        Layout.minimumWidth: 200
                        Layout.minimumHeight: 200
                    }
                }
            }
            Tab {
                title: "Folder select Settings"
                ScrollView {
                        id: scrollView
                        anchors {
                            left: parent.left
                            right: parent.right
                            top: parent.top
                            bottom: bottomBar.top
                            leftMargin: 12
                        }
                        ColumnLayout {
                            spacing: 8
                            Item { Layout.preferredHeight: 4 } // padding
                            Label {
                                font.bold: true
                                text: "File dialog properties:"
                            }
                            CheckBox {
                                id: fileDialogModal
                                text: "Modal"
                                checked: true
                                Binding on checked { value: fileDialog.modality != Qt.NonModal }
                            }
                            CheckBox {
                                id: fileDialogSelectFolder
                                text: "Select Folder"
                                Binding on checked { value: fileDialog.selectFolder }
                            }
                            CheckBox {
                                id: fileDialogSelectExisting
                                text: "Select Existing Files"
                                checked: true
                                Binding on checked { value: fileDialog.selectExisting }
                            }
                            CheckBox {
                                id: fileDialogSelectMultiple
                                text: "Select Multiple Files"
                                Binding on checked { value: fileDialog.selectMultiple }
                            }
                            CheckBox {
                                id: fileDialogOpenFiles
                                text: "Open Files After Accepting"
                            }
                            CheckBox {
                                id: fileDialogSidebarVisible
                                text: "Show Sidebar"
                                checked: fileDialog.sidebarVisible
                                Binding on checked { value: fileDialog.sidebarVisible }
                            }
                            CheckBox {
                                id: fileDialogVisible
                                text: "Visible"
                                Binding on checked { value: fileDialog.visible }
                            }
                            Label {
                                text: "<b>current view folder:</b> " + fileDialog.folder
                            }
                            Label {
                                text: "<b>name filters:</b> {" + fileDialog.nameFilters + "}"
                            }
                            Label {
                                text: "<b>current filter:</b>" + fileDialog.selectedNameFilter
                            }
                            Label {
                                text: "<b>chosen files:</b> " + fileDialog.fileUrls
                            }
                            Label {
                                text: "<b>chosen single path:</b> " + fileDialog.fileUrl
                            }
                        }
                    }
            }
        }


        //button1.onClicked: messageDialog.show(qsTr("Button 1 pressed"))
        //button2.onClicked: messageDialog.show(qsTr("Button 2 pressed"))
        //button3.onClicked: messageDialog.show(qsTr("Button 3 pressed"))


        FileDialog {
            id: fileDialog

            //selectFolder: true
            /*
            visible: fileDialogVisible.checked
            modality: fileDialogModal.checked ? Qt.WindowModal : Qt.NonModal
            title: fileDialogSelectFolder.checked ? "Choose a folder" :
                (fileDialogSelectMultiple.checked ? "Choose some files" : "Choose a file")
            selectExisting: fileDialogSelectExisting.checked
            selectMultiple: fileDialogSelectMultiple.checked
            selectFolder: fileDialogSelectFolder.checked
            */

            nameFilters: [ "Image files (*.png *.jpg)", "All files (*)" ]
            selectedNameFilter: "All files (*)"

            //sidebarVisible: fileDialogSidebarVisible.checked
            //mainForm tabView tabImageSort splitView

            onAccepted: {
                folderModel.folder = fileUrl + "/"

                console.log("Accepted: " + fileUrls)
                for (var i = 0; i < fileUrls.length; ++i)
                    Qt.openUrlExternally(fileUrls[i])
                /*
                if (fileDialogOpenFiles.checked)
                    for (var i = 0; i < fileUrls.length; ++i)
                        Qt.openUrlExternally(fileUrls[i])
                */
            }
            onRejected: { console.log("Rejected") }
        }

/*
        FolderListModel {
            id: folderModel
            //folder: 'D:\RUDB\pictures\social'
            nameFilters: ["*.*"]
        }
*/
    } //mainForm

    MessageDialog {
        id: messageDialog
        title: qsTr("May I have your attention, please?")

        function show(caption) {
            messageDialog.text = caption;
            messageDialog.open();
        }
    }



/*
    FileDialog {
        id: fileDialog
        title: "Please choose a file"
        selectFolder: true
        onAccepted: {
            console.log("You chose: " + fileDialog.fileUrls)
            //Qt.quit()
        }
        onRejected: {
            console.log("Canceled")
            //Qt.quit()
        }
        //Component.onCompleted: visible = true
    }
*/
/*
    ListView {
         width: 200; height: 400

         FolderListModel {
             id: folderModel
             folder: 'D:\RUDB\pictures\social'
             nameFilters: ["*.*"]
         }

         Component {
             id: fileDelegate
             Text { text: fileName }
         }

         model: folderModel
         delegate: fileDelegate
     }*/
}

Trisch
Чтобы добавить в TableView данные, надо их добавить в model которая прикручена к TableView.
Количество столбцев зависит от модели.

К примеру. у тебя есть модель:
ListModel {
    id: lModel
}


и ты в нее добавляешь данные:

lModel.append({"table1": "data1", "table2": "data2", "table3": "data3"})


и того у тебя будет три столбца с данніми data1, data2, data3.
Данные в модель можно передавать с помощью ассоциативного массива из javascript.

Так же надо иметь ввиду, что структура модели, зависит от первого массива данных, который в нее добавляют или изночально надо задать в ручную.
Для просмотра полной версии этой страницы, пожалуйста, пройдите по ссылке.
Форум IP.Board © 2001-2024 IPS, Inc.