Qt:将C ++类暴露给QML时出错
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Qt:将C ++类暴露给QML时出错相关的知识,希望对你有一定的参考价值。
我在运行应用程序时遇到同样的错误:
qrc:/main.qml:13:ReferenceError:未定义_myClass
这个bug在哪里?
此外,如果我想将信号myIntChanged连接到插槽,我应该在哪里放置连接?在main.cpp或构造函数MyClass中?
myclass.h
#ifndef MYCLASS_H
#define MYCLASS_H
#include <QObject>
#include <QString>
#include <QDebug>
#include <QTimer>
class MyClass : public QObject
{
Q_OBJECT
public:
MyClass(QObject *parent = 0);
Q_PROPERTY(int myInt READ getMyInt WRITE setMyInt NOTIFY myIntChanged)
int myInt;
inline int getMyInt() { return myInt; }
inline void setMyInt(int _value) { myInt = _value; }
private:
void initVariables();
QTimer *timer;
private slots:
void editVariables();
signals:
void myIntChanged();
};
#endif // MYCLASS_H
myclass.cpp
#include "myclass.h"
MyClass::MyClass(QObject *parent) : QObject (parent)
{
initVariables();
timer = new QTimer(this);
connect(timer, SIGNAL(timeout()), this, SLOT(editVariables()));
timer -> start(3000);
}
void MyClass::initVariables()
{
myInt = 0;
}
void MyClass::editVariables()
{
myInt = myInt + 1;
qDebug() << "myclass.cpp: timeout: variables edited.";
}
main.cpp中
#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>
#include "myclass.h"
int main(int argc, char *argv[])
{
#if defined(Q_OS_WIN)
QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
#endif
QGuiApplication app(argc, argv);
QQmlApplicationEngine engine;
engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
if (engine.rootObjects().isEmpty())
return -1;
MyClass *myClass = new MyClass();
engine.rootContext() -> setContextProperty("_myClass", myClass);
return app.exec();
}
main.qml
import QtQuick 2.9
import QtQuick.Window 2.2
Window {
visible: true
width: 640
height: 480
title: qsTr("Exposed C++ Class")
Text {
anchors.top: parent.top; anchors.topMargin: 30
anchors.left: parent.left; anchors.leftMargin: 30
text: _myClass.myInt
}
}
答案
问题是由于load()
语句正在加载.qml文件,在读取它并验证变量是否存在时,他们意识到这个对象不存在,因为它通过setContextProperty()
传递给它们,一个可能的解决方案是通过在加载.qml之前反对它:
int main(int argc, char *argv[])
{
#if defined(Q_OS_WIN)
QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
#endif
QGuiApplication app(argc, argv);
QQmlApplicationEngine engine;
MyClass *myClass = new MyClass();
engine.rootContext()->setContextProperty("_myClass", myClass);
engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
if (engine.rootObjects().isEmpty())
return -1;
return app.exec();
}
它没有更新,因为它没有通过你声明的信号通知,正确的做法是每次属性更改时发出一个信号,你必须修改一些方法:
inline void setMyInt(int _value) {
if(myInt == _value)
return;
myInt = _value;
emit myIntChanged();
}
void MyClass::editVariables()
{
setMyInt(getMyInt()+1);
qDebug() << "myclass.cpp: timeout: variables edited.";
}
以上是关于Qt:将C ++类暴露给QML时出错的主要内容,如果未能解决你的问题,请参考以下文章
为啥我在实现委托以将值从子 swift 类传递给父目标 C 类时出错?