主要通过qml实现listvie功能,主要包括右键菜单,滚动条,拖动改变内容等,c++ 与 qml之间的变量和函数的调用。
main.cpp
#include <QQuickItem>
#include <QQmlContext>
#include "testlistmodel.h"
int main(int argc, char *argv[])
{
QGuiApplication app(argc, argv);
QQmlApplicationEngine engine;
qmlRegisterType<TestListModel>("TestListModel", 1, 0, "TestListModel");
engine.load(QUrl(QStringLiteral("qrc:/ui1.qml")));
QObject* root = engine.rootObjects().first();
QString retVal;
QVariant message = "Hello from c++";
QVariant returnedValue;
QQmlProperty(root,"testmsg").write("hello,world");
qDebug()<<"Cpp get qml property height222"<<root->property("msg");
bool ret =QMetaObject::invokeMethod(root,"setSignalB",
Q_RETURN_ARG(QVariant,returnedValue),
Q_ARG(QVariant,message),
Q_ARG(QVariant,8));
qDebug()<<"returnedValue"<<returnedValue<<root<<ret;
return app.exec();
}
listview 的model 代码
TestListModel.h
#ifndef TESTLISTMODEL_H
#define TESTLISTMODEL_H
#include <QAbstractListModel>
typedef struct Student
{
int id;
QString name;
QString sex;
}pStudent;
class TestListModel : public QAbstractListModel
{
Q_OBJECT
public:
explicit TestListModel(QObject *parent = nullptr);
int rowCount(const QModelIndex &parent) const;
QVariant data(const QModelIndex &index, int role) const;
virtual QHash<int, QByteArray> roleNames() const;
Qt::ItemFlags flags(const QModelIndex &index) const override;
Q_INVOKABLE void modifyItemText(int row1,int row2);
Q_INVOKABLE void add();
enum MyType{
ID=Qt::UserRole+1,
Name,
Sex
};
private:
QVector<Student> m_studentList;
signals:
void layoutChanged();
};
#endif // TESTLISTMODEL_H
TestListModel.cpp
#include "testlistmodel.h"
#include <QDebug>
TestListModel::TestListModel(QObject *parent)
: QAbstractListModel{parent}
{
for(int i=0;i<20;i++)
{
Student oneData;
oneData.id = i;
oneData.name = QString("张三%1").arg(i);
if(i%2==0)
{
oneData.sex = "female" ;
}
else
{
oneData.sex = "male" ;
}
//qDebug()<<"TestListModel"<<m_studentList.size();
m_studentList.append(oneData);
}
}
int TestListModel::rowCount(const QModelIndex &parent) const
{
//qDebug()<<"rowCount"<<m_studentList.size();
return m_studentList.size();
}
QVariant TestListModel::data(const QModelIndex &index, int role) const
{
// qDebug()<<"TestListModel::data11111111111"<<index.isValid();
QVariant var;
if ( !index.isValid() )
{
return QVariant();
}
int nRow = index.row();
int nColumn = index.column();
if(Qt::UserRole+1 == role)
{
var = QVariant::fromValue(m_studentList.at(nRow).id);
}
else if(Qt::UserRole+2 == role)
{
var = QVariant::fromValue(m_studentList.at(nRow).name);
// qDebug()<<"m_listData.at(nRow).name"<<m_listDa

1894

被折叠的 条评论
为什么被折叠?



