• 3186阅读
  • 1回复

zhengtianzuo系列-QmlTableView [复制链接]

上一主题 下一主题
离线zhengtianzuo
 

只看楼主 倒序阅读 楼主  发表于: 2017-10-19
使用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
博客地址: https://blog.csdn.net/zhengtianzuo06
Github: https://github.com/zhengtianzuo
个人产品: https://github.com/zhengtianzuo/Silk
产品网站: http://www.camelstudio.cn
离线big_mouse

只看该作者 1楼 发表于: 2020-04-22
快速回复
限100 字节
 
上一个 下一个