最近在搞qt的qml编程,发现相对于WPF这个qt可是相当的繁琐,所以把重点的内容记录一下
- ListModelList
- TableListModel
- 自定义Object
- 异步等待
1 ListModelList
mylistmodel.h 需要重写 QHash<int,QByteArray> roleNames() const override;其他的是QT自动生成的
c++
#ifndef MYLISTMODEL_H
#define MYLISTMODEL_H
#include <QAbstractListModel>
class NameObj
{
public:
//初始化构造器
NameObj(const QString &name,const int &value):name_(name),value_(value){
}
QString name() const{
return name_;
}
int value() const{
return value_;
}
private:
//私有变量
QString name_;
int value_;
};
class MylistModel : public QAbstractListModel
{
Q_OBJECT
public:
explicit MylistModel(QObject *parent = nullptr);
enum NameObjRoles {
NameRole = Qt::UserRole + 1,
ValueRole
};
int rowCount(const QModelIndex &parent = QModelIndex()) const override;
QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override;
void addNameObj(NameObj const & p);//这是我自己增加的一个方法 可以不加
QHash<int,QByteArray> roleNames() const override;
private:
QList<NameObj> _data;
};
#endif // MYLISTMODEL_H
#include "mylistmodel.h"
MylistModel::MylistModel(QObject *parent)
: QAbstractListModel(parent)
{
}
//QVariant MylistModel::headerData(int section, Qt::Orientation orientation, int role) const
//{
// // FIXME: Implement me!
//}
int MylistModel::rowCount(const QModelIndex &parent) const
{
// For list models only the root node (an invalid parent) should return the list's size. For all
// other (valid) parents, rowCount() should return 0 so that it does not become a tree model.
if (parent.isValid())
return 0;
return _data.count();
// FIXME: Implement me!
}
QVariant MylistModel::data(const QModelIndex &index, int role) const
{
if (!index.isValid())
return QVariant();
if (index.row() >= _data.count() || index.row() < 0)
return QVariant();
const NameObj &obj = _data[index.row()];
if (role == NameRole)
return obj.name();
else if (role == ValueRole)
return obj.value();
return QVariant();
}
void MylistModel:: addNameObj(NameObj const & p) {
beginInsertRows(QModelIndex(), rowCount(), rowCount());
_data << p;
endInsertRows();
}
QHash<int,QByteArray> MylistModel:: roleNames() const {
QHash<int,QByteArray> roles;
roles[NameRole]="name";
roles[ValueRole]="value";
return roles;
}
main.cpp
QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
QGuiApplication app(argc, argv);
QQmlApplicationEngine engine;
MylistModel data;
NameObj p1("Dean", 176);
data.addNameObj(p1);
NameObj p2("Tgeb", 178);
data.addNameObj(p2);
qmlRegisterType<MylistModel>("MyModel", 1, 1, "MyModellist");
engine.rootContext()->setContextProperty("mymodel", &data);//直接注册 QT版本5.14
//如果高于这个5.15的请使用qmlRegisterSingletonInstance会更好一点
engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
if (engine.rootObjects().isEmpty())
return -1;