作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我试图使用qmlRegisterSingletonType
创建单例属性,但是当我尝试访问QML中的对象时,控制台日志中出现以下错误:
qrc:/qml/MyQml.qml:21 Element is not creatable.
#include <QObject>
#include <QJsonObject>
#include <QVariantMap>
#include <QQmlEngine>
class TestSingletonType : public QObject
{
Q_OBJECT
Q_DISABLE_COPY(TestSingletonType)
TestSingletonType(QObject *parent = nullptr) {}
public:
// To maintain single object of the class
static QObject *qmlInstance(QQmlEngine *engine, QJSEngine *scriptEngine)
{
Q_UNUSED(engine);
Q_UNUSED(scriptEngine);
if (theInstance == NULL)
theInstance = new TestSingletonType();
return theInstance;
}
private:
static QObject *theInstance; // I have set it to NULL in Cpp file
};
int main(int argc, char *argv[])
{
QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
QGuiApplication app(argc, argv);
QQmlApplicationEngine engine;
qmlRegisterSingletonType<TestSingletonType>("com.my.TestSingletonType", 1, 0, "TestSingletonType", &TestSingletonType::qmlInstance);
// Rest of the code to load the QML
return app.exec();
}
import QtQuick 2.0
import QtQuick.Controls 2.0
import com.my.TestSingletonType 1.0
Item {
TestSingletonType { <---- Getting error on this line
id: mySingleClass
}
// Rest of my code which uses "mySingleClass"
}
qmlRegisterType
,那么它可以正常工作,但不能与
qmlRegisterSingletonType
一起工作。
最佳答案
错误很明显:由于在回调(qmlInstance方法)中已经创建了一个单例,因此不会在QML中创建它,您只需要访问该方法的属性即可。 typeName(“TestSingletonType”)是ID。
Item {
// binding property
foo_property : TestSingletonType.foo_value
// update singleton property
onAnotherPropertyChanged: TestSingletonType.another_prop = anotherProperty
}
// listen singleton signal
Connections{
target: TestSingletonType
onBarChanged: bar_object.bar_property = bar
}
关于c++ - Qt Quick2为单例类类型创建qmlRegisterSingletonType,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62104907/
我最近购买了《C 编程语言》并尝试了 Ex 1-8这是代码 #include #include #include /* * */ int main() { int nl,nt,nb;
早上好!我有一个变量“var”,可能为 0。我检查该变量是否为空,如果不是,我将该变量保存在 php session 中,然后调用另一个页面。在这个新页面中,我检查我创建的 session 是否为空,
我正在努力完成 Learn Python the Hard Way ex.25,但我无法理解某些事情。这是脚本: def break_words(stuff): """this functio
我是一名优秀的程序员,十分优秀!