使用自定义委托通过 TableView 编辑 QStandardItemModel

Edit QStandardItemModel via TableView with Custom Delegate

我有一个通过 QML Table 视图显示的 QStandardItemModel。

这是模型:

class mystandardmodel: public QStandardItemModel
{

public:
    mystandardmodel();
    enum Role {
         role1=Qt::UserRole,
         role2
     };

     explicit mystandardmodel(QObject * parent = 0): QStandardItemModel(parent){}
     //explicit mystandardmodel( int rows, int columns, QObject * parent = 0 )
     //    : QStandardItemModel(rows, columns, parent){}

     QHash<int, QByteArray> roleNames() const{
          QHash<int, QByteArray> roles;
          roles[role1] = "one";
          roles[role2] = "two";
          return roles;
 }
};

这是使用自定义委托显示模型的方式:

    TableView {
        id: tableView2
        x: 69
        y: 316
        width: 318
        height: 150
        TableViewColumn {
            title: "Parameter Name"
            role: "one"
        }
        TableViewColumn {
            title: "Value"
            role: "two"
            delegate: myDelegate
        }
        model: myTestModel
    }

    Component {
        id: myDelegate
        Loader {
            property var roleTwo: model.two
            sourceComponent: if(typeof(roleTwo)=='boolean') {
                                 checkBoxDelegate}
                             else { stringDelegate}
        }
    }

    Component {
        id: checkBoxDelegate
        CheckBox{text: roleTwo}
    }

    Component {
        id: stringDelegate
        TextEdit {text: roleTwo}
    }

我这样填充模型:

 mystandardmodel* mysmodel=new mystandardmodel(0);
 QStandardItem* it = new QStandardItem();
 it->setData("data1", mystandardmodel::role1);
 it->setData(true, mystandardmodel::role2);
 it->setCheckable(true);
 it->setEditable(true);
 mysmodel->appendRow(it);
 QStandardItem* it2 = new QStandardItem();
 it2->setData("data2",mystandardmodel::role1);
 it2->setData("teststring",mystandardmodel::role2);
 mysmodel->appendRow(it2);

如何使模型可编辑,以便使用复选框或编辑文本传输回模型?

编辑:我尝试遵循 In QML TableView when clicked edit a data (like excel) 中的建议并使用 set model:

Component {
    id: myDelegate
    Loader {
        property var roleTwo: model.two
        property int thisIndex: model.index
        sourceComponent: if(typeof(roleTwo)=='boolean') {
                             checkBoxDelegate}
                         else { stringDelegate}
    }
}

Component {
    id: checkBoxDelegate
    CheckBox{text: roleTwo
        onCheckedChanged: {
            myTestModel.setData(0,"two",false)
            console.log('called',thisIndex)
        }
    }

}

Component {
    id: stringDelegate
    TextEdit {text: roleTwo
        onEditingFinished: {
            myTestModel.setData(thisIndex,"two",text)
           console.log('called',thisIndex)
        }
    }
}

索引没问题,但似乎没有效果(我添加了第二个Table具有相同模型的视图,但是如果我在首先Table查看)

使用 setData() 可能是一个选项,但它需要一个整数值来指示在 QML 中不可访问的角色,或者说是不优雅。

更好的选择是创建一个新的 Q_INVOKABLE。由于更新是在视图中给出的,因此除了引起奇怪的事件外,没有必要通知它。

我们使用几何和 TableViewrowAt() 方法来获取行。

示例如下:

main.cpp

#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>
#include <QStandardItemModel>

class MyStandardModel: public QStandardItemModel
{
    Q_OBJECT
public:
    enum Role {
        role1=Qt::UserRole+1,
        role2
    };

    using QStandardItemModel::QStandardItemModel;

    QHash<int, QByteArray> roleNames() const{
        QHash<int, QByteArray> roles;
        roles[role1] = "one";
        roles[role2] = "two";
        return roles;
    }

    Q_INVOKABLE void updateValue(int row, QVariant value, const QString &roleName){

        int role = roleNames().key(roleName.toUtf8());
        QStandardItem *it = item(row);
        if(it){
            blockSignals(true);
            it->setData(value, role);
            Q_ASSERT(it->data(role)==value);
            blockSignals(false);
        }

    }
};

int main(int argc, char *argv[])
{
    QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);

    QGuiApplication app(argc, argv);

    MyStandardModel model;

    for(int i=0; i< 10; i++){
        auto item = new QStandardItem;
        item->setData(QString("data1 %1").arg(i), MyStandardModel::role1);
        if(i%2 == 0)
            item->setData(true, MyStandardModel::role2);
        else {
            item->setData(QString("data2 %1").arg(i), MyStandardModel::role2);
        }
        model.appendRow(item);
    }
    QQmlApplicationEngine engine;
    engine.rootContext()->setContextProperty("myTestModel", &model);
    engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
    if (engine.rootObjects().isEmpty())
        return -1;

    return app.exec();
}

#include "main.moc"

main.qml

import QtQuick 2.9
import QtQuick.Window 2.2
import QtQuick.Controls 1.4

Window {
    visible: true
    width: 640
    height: 480
    title: qsTr("Hello World")

    TableView {
        id: tableView2
        anchors.fill: parent
        TableViewColumn {
            title: "Parameter Name"
            role: "one"
        }
        TableViewColumn {
            title: "Value"
            role: "two"
            delegate: myDelegate
        }
        model: myTestModel
    }

    Component {
        id: myDelegate
        Loader {
            property var roleTwo: model.two
            sourceComponent: typeof(roleTwo)=='boolean'? checkBoxDelegate: stringDelegate
        }
    }

    Component {
        id: checkBoxDelegate
        CheckBox{
            checked: roleTwo
            onCheckedChanged:{
                var pos = mapToGlobal(0, 0)
                var p = tableView2.mapFromGlobal(pos.x, pos.y)
                var row = tableView2.rowAt(p.x, p.y)
                if(row >= 0)
                    myTestModel.updateValue(tableView2.row, checked, "two")
            }
        }
    }

    Component {
        id: stringDelegate
        TextField {
            text: roleTwo
            onEditingFinished: {
                var pos = mapToGlobal(0, 0)
                var p = tableView2.mapFromGlobal(pos.x, pos.y)
                var row = tableView2.rowAt(p.x, p.y)
                if(row >= 0)
                    myTestModel.updateValue(tableView2.row, text, "two")
            }

        }
    }
}

完整的例子可以在下面link.

中找到

您可以直接将值设置为 model.two,这将使用正确的角色和索引自动调用 setData

import QtQuick 2.10
import QtQuick.Controls 2.0 as QQC2
import QtQuick.Controls 1.4 as QQC1
import QtQuick.Layouts 1.3

QQC2.ApplicationWindow {
    visible: true
    width: 640
    height: 480

    ColumnLayout {
        anchors.fill: parent
        Repeater {
            model: 2
            QQC1.TableView {
                Layout.fillWidth: true
                Layout.fillHeight: true
                QQC1.TableViewColumn {
                    title: "Parameter Name"
                    role: "one"
                }
                QQC1.TableViewColumn {
                    title: "Value"
                    role: "two"
                    delegate: Loader {
                        property var modelTwo: model.two
                        sourceComponent: typeof(model.two) ==='boolean' ? checkBoxDelegate : stringDelegate
                        function updateValue(value) {
                            model.two = value;
                        }
                    }
                }
                model: myModel
            }
        }
    }

    Component {
        id: checkBoxDelegate
        QQC1.CheckBox {
            text: modelTwo
            checked: modelTwo
            onCheckedChanged: {
                updateValue(checked);
                checked = Qt.binding(function () { return modelTwo; }); // this is needed only in QQC1 to reenable the binding
            }
        }
    }

    Component {
        id: stringDelegate
        TextEdit {
            text: modelTwo
            onTextChanged: updateValue(text)
        }
    }
}

如果这对你来说仍然太冗长且不够明确(对我来说),你可以使用类似下面的内容,其中大部分逻辑都在 Loader 中,具体委托只是告知什么是 属性 应该设置和更新值的位置:

delegate: Loader {
    id: loader
    sourceComponent: typeof(model.two) ==='boolean' ? checkBoxDelegate : stringDelegate
    Binding {
        target: loader.item
        property: "editProperty"
        value: model.two
    }
    Connections {
        target: loader.item
        onEditPropertyChanged: model.two = loader.item.editProperty
    }
}

//...

Component {
    id: checkBoxDelegate
    QQC1.CheckBox {
        id: checkbox
        property alias editProperty: checkbox.checked
        text: checked
    }
}

Component {
    id: stringDelegate
    TextEdit {
        id: textEdit
        property alias editProperty: textEdit.finishedText // you can even use a custom property
        property string finishedText
        text: finishedText
        onEditingFinished: finishedText = text
    }
}