使用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 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> 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
作者 | 郑天佐 |
---|---|
278969898 | |
主页 | http://www.camelstudio.cn/ |
邮箱 | [email protected] |
博客 | http://blog.csdn.net/zhengtianzuo06/ |
github | https://github.com/zhengtianzuo |
QQ群 | 199672080 |