我是 Qt 新手,正在尝试在 Qt 中创建自定义属性。 为了保持简短,我在这里合并了 .h 和 .cpp 文件,但它们在我的主项目中是不同的。 我的main.cpp是
#include <QApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>
#include "message.h"
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
QQmlApplicationEngine engine;
Message msg;
engine.rootContext()->setContextProperty("msg", &msg);
engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
qRegisterMetaType<MessageBody*>("MessageBody*");
return app.exec();
}
我的message.h是
#include<messageBody.h>
class Message : public QObject
{
Q_OBJECT
Q_PROPERTY(MessageBody* body READ body WRITE setBody NOTIFY bodyChanged)
MessageBody ob;
public:
MessageBody* body()
{
return &ob;
}
void setBody(MessageBody* body)
{
ob.textUpdate(body->text());
emit bodyChanged();
}
signals:
void bodyChanged();
};
我的messageBody.h是
class MessageBody : public QObject
{
Q_OBJECT
Q_PROPERTY(QString text READ text WRITE textUpdate NOTIFY textChanged)
QString ori_text;
public:
void textUpdate(const QString& new_txt)
{
if(new_txt != ori_text)
{
ori_text=new_txt;
emit textChanged();
}
}
QString text()
{
return ori_text;
}
signals:
void textChanged();
};
我的 main.qml 是
import QtQuick 2.3
import QtQuick.Controls 1.2
ApplicationWindow {
visible: true
width: 640
height: 480
title: qsTr("Hello World")
Text{
msg.body: "Hello, world!" //"Error here."
//I am expecting MessageBody::textUpdate()
//to get called i.e write method of Property
}
}
执行时出现错误
qrc:/main.qml:18 Cannot assign to non-existent property "msg"
感谢您的帮助。
最佳答案
我没有 100% 得到你想要实现的目标,但也许是这样的:
main.qml
import QtQuick 2.3
import QtQuick.Controls 1.2
ApplicationWindow {
visible: true
width: 640
height: 480
title: qsTr("Hello World")
Text{
text: msg.body.text
}
Component.onCompleted: {
msg.body.text = "Hello, world!"
}
}
main.cpp
#include <QApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>
#include "message.h"
#include "MessageBody.h"
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
QQmlApplicationEngine engine;
qRegisterMetaType<MessageBody*>("MessageBody");
qRegisterMetaType<Message *>("Message");
Message msg;
engine.rootContext()->setContextProperty("msg", &msg);
engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
return app.exec();
}
这个有用吗?
关于c++ - 使用 C++ 在 Qt 中创建自定义属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30161980/