Qt 使用自定义 QObject 类型调用 qml 函数 [英] Qt invoking qml function with custom QObject type
问题描述
我想从 C++ 调用 qml 方法,将自定义类型作为参数传递.
I want to invoke a qml method from c++ passing as a parameter a custom type.
这是我的自定义类型(*注意我发布的所有代码都不是我正在使用的,我已经提取了相关部分,因此如果您尝试编译,则可能必须进行一些更改)
This is my custom type (*Note that all the code I post is not exactly what i'm using, i've extracted the relevant parts, so if you try to compile it is possible that some changes have to be made)
自定义.h
class Custom : public QObject
{
Q_OBJECT
Q_PROPERTY(QString ssid READ getSSID WRITE setSSID)
public:
Q_INVOKABLE const QString& getSSID() {
return m_ssid;
}
Q_INVOKABLE void setSSID(const QString& ssid) {
m_ssid = ssid;
}
}
private:
QString m_ssid;
};
Q_DECLARE_METATYPE(NetworkInfo)
自定义.cpp
Custom::Custom(): QObject() {
setSSID("ABC");
}
Custom::Custom(const Custom & other): QObject() {
setSSID(other.getSSID());
}
这是我调用qml方法的地方
This is where I call the qml method
void MyClass::myMethod(const Custom &custom) {
QMetaObject::invokeMethod(&m_item,
"qmlMethod", Q_ARG(QVariant, QVariant::fromValue(custom)));
}
where QQuickItem&m_item
我已将 Custom 声明为 QML 和 QT 元类型
I have declared Custom as QML and QT meta types
qmlRegisterType<Custom>("com.mycustom", 1, 0, "Custom");
当我尝试访问 qml 中的参数时
When i try to access the parameter inside the qml
import com.mycustom 1.0
function(custom) {
console.log(custom.ssid)
}
我明白了
qml: undefined
如果我做 console.log(custom)
我得到
qml: QVariant(Custom)
所以,我想说我的类型已正确导入 Qt(我使用它没有问题,直接在 Qml 中使用
so, i'd say my type is correctly imported into Qt (I have used it without problems instantiating it directly in Qml with
Custom {
....
}
现在,问题:)
为什么我无法访问 ssid 属性?
Why can't I access the ssid property ?
推荐答案
由于您似乎已正确注册了所有内容,因此您可能会遇到 QML 有时会发生的错误,其中对象似乎卡在 QVariant 包装中.尝试以下操作,看看它是否有效.
Since you seem to have registered everything correctly, you might be encounting a bug that sometimes happen with QML where objects seem to be stuck in a QVariant wrapping. Try the following and see if it work.
import com.mycustom 1.0
property QtObject temp
function(custom) {
temp = custom;
console.log(temp.ssid);
}
有时强制您的实例成为 QtObject 会移除烦人的QVariant 包装器"并解决问题.
Sometimes forcing your instance to be a QtObject will remove the annoying "QVariant wrapper" and solve the issue.
这篇关于Qt 使用自定义 QObject 类型调用 qml 函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!