查看完整版本: [-- zhengtianzuo系列-QmlTableView --]

QTCN开发网 -> Qt代码秀 -> zhengtianzuo系列-QmlTableView [打印本页] 登录 -> 注册 -> 回复主题 -> 发表主题

zhengtianzuo 2017-10-19 17:25

zhengtianzuo系列-QmlTableView

使用QtQuick的MVC模式
新建c++类继承于QAbstractTableModel, 并实现几个重要方法:

CPP中:
```
class QmlTableViewModel : public QAbstractTableModel
{
    Q_OBJECT
public:
    explicit QmlTableViewModel();
    int rowCount(const QModelIndex & parent = QModelIndex()) const Q_DECL_OVERRIDE;
    int columnCount(const QModelIndex &parent = QModelIndex()) const Q_DECL_OVERRIDE;
    QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const Q_DECL_OVERRIDE;
    QHash<int, QByteArray> roleNames() const Q_DECL_OVERRIDE;

    Q_INVOKABLE void Add(QString one, QString two, QString three);
    Q_INVOKABLE void Set(int row, int column, QString text);
    Q_INVOKABLE void Del();
    Q_INVOKABLE void Refresh();
private:
   QVector<QVector<QString>> m_aryData;
};
```

注册c++类:

```
    QmlTableViewModel model;
    engine.rootContext()->setContextProperty("theModel", &model);
```

rowCount 获取总行数
columnCount 获取总列数
data 获取当前数据
roleNames mvc别名

Qml中:

```
    QmlTableView{
        id: qmlTableView
        height: frmWindow.height - 40
        width: parent.width
        tableView.itemDelegate:Rectangle {
            TextField{
                id: textField
                height: 25
                text: styleData.value
                selectByMouse: true
                onEditingFinished: {
                    theModel.Set(styleData.row, styleData.column, textField.text);
                }
                visible: (styleData.column !== 0)
            }
            Image{
                id: image
                height: 25
                width: 25
                source: "qrc:/Face.png"
                visible: (styleData.column === 0)
            }
        }
        tableView.rowDelegate: Rectangle {
            height: 25
        }
    }
```



需要完整代码请访问 QtQuickExamples

big_mouse 2020-04-22 09:20


查看完整版本: [-- zhengtianzuo系列-QmlTableView --] [-- top --]



Powered by phpwind v8.7 Code ©2003-2011 phpwind
Gzip disabled