先放一个界面效果吧!

说明:该演示程序为一个App管理程序,可以将多个App进行吸入管理。
(动画中的RedRect为一个带有QSplashScreen的独立应用程序)
- 左侧边栏用的是QQuickView进行.qml文件的加载(即QtQuick环境)
- 右侧是用layout进行QWidget的融入(QtWidgets环境)
- 期间会有多次qml & c++的交互
一、qml中访问c++中的内容
关键点:.h中继承QObject、Q_DECLARE_METATYPE;.cpp中qmlRegisterType
cpp
class AppInfo : public QObject
{
Q_OBJECT
Q_PROPERTY(QString showName READ showName WRITE setShowName NOTIFY showNameChanged)
Q_PROPERTY(QString realName READ realName WRITE setRealName NOTIFY realNameChanged)
Q_PROPERTY(QString coreName READ coreName WRITE setCoreName NOTIFY coreNameChanged)
Q_PROPERTY(QString iconPath READ iconPath WRITE setIconPath NOTIFY iconPathChanged)
public:
AppInfo(QObject* parent = nullptr);
AppInfo(const QString& showName, const QString& realName, const QString& coreName, const QString& iconPath, QObject* parent = nullptr);
AppInfo(const AppInfo& other);
AppInfo& operator=(const AppInfo& other);
bool operator==(const AppInfo& other);
QString showName() const;
QString realName() const;
QString coreName() const;
QString iconPath() const;
void setShowName(const QString& showName);
void setRealName(const QString& realName);
void setCoreName(const QString& coreName);
void setIconPath(const QString& iconPath);
signals:
void showNameChanged();
void realNameChanged();
void coreNameChanged();
void iconPathChanged();
private:
QString showName_;
QString realName_;
QString coreName_;
QString iconPath_;
};
Q_DECLARE_METATYPE(AppInfo)
cpp
qmlRegisterType<AppInfo>();
这样以后,
1.1.可以直接在qml中进行该类的实例化,进而进行访问(qmlRegisterType时需要添加参数);

1.2.也可以直接在其他类中直接返回该类指针,直接给qml进行使用(当然前提也是其他类也进行了注册,已经在qml里实例化了)。
1.3.还可以再c++处实例化,然后设置到qml上下文中

2.1.也可以直接继承QAbstractListModel等类,进行实例化,qml中可以直接访问相关属性

主要在于红框中的方法的重写。
二、c++中访问qml中的内容
主要在于从qml上下文中获取根QObject*,进而通过findChild进行相关元素的获取。进而通过QMetaObject::invokeMethod进行相关qml中function的调用:


相关注意点:
qml中访问只能访问类的指针,不能访问类对象;
qmlRegisterType注册类时,带了namespace的类,类指针在qml中是不能够访问的。