根据Qt5文档:公开方法,包括qt插槽继承自QObject的C++类的所有公共插槽,在这里可以从QML访问我所做的:
class MyClass : public QObject
{
Q_OBJECT
public slots:
void doStuffFromQmlSlot()
{
qDebug() << Q_FUNC_INFO;
}
public:
MyClass()
{
qDebug() << Q_FUNC_INFO;
}
};
我的main.cpp包含:
MyClass myClass;
QQmlEngine engine;
engine.rootContext()->setContextProperty( "myclass", &myClass );
QQmlComponent component( &engine, QUrl::fromLocalFile("qml/qtquick-01/main.qml") );
component.create();
import QtQuick 2.0
Rectangle {
width: 360
height: 360
Text {
text: qsTr("Hello World")
anchors.centerIn: parent
}
MouseArea {
anchors.fill: parent
onClicked: {
myclass.doStuffFromQmlSlot();
Qt.quit();
}
}
}
实际上,QtCreator似乎将公开的myclass对象识别到QML中,因为它支持类名(myclass)和公共槽doStuffFromQmlSlot()的自动完成。不幸的是,当我运行应用程序时,我得到了以下错误:
知道我做错了什么吗?
发布于 2014-03-08 11:25:34
我重用了您的qml文件,在QtCreator中启动了一个新项目。
请在下面找到我用来成功编译和使用应用程序的文件:
项目文件: test.pro
# The .cpp file which was generated for your project. Feel free to hack it.
SOURCES += main.cpp
# Please do not modify the following two lines. Required for deployment.
include(qtquick2applicationviewer/qtquick2applicationviewer.pri)
qtcAddDeployment()
HEADERS += myclass.h
#include <QObject>
#include <qdebug.h>
class MyClass : public QObject
{
Q_OBJECT
public slots:
void doStuffFromQmlSlot()
{
qDebug() << Q_FUNC_INFO;
}
public:
MyClass()
{
qDebug() << Q_FUNC_INFO;
}
};
#include <QtGui/QGuiApplication>
#include "qtquick2applicationviewer.h"
#include <QQmlContext>
#include "myclass.h"
int main(int argc, char *argv[])
{
QGuiApplication app(argc, argv);
MyClass myClass;
QtQuick2ApplicationViewer viewer;
viewer.rootContext()->setContextProperty("myclass", &myClass);
viewer.setMainQmlFile(QStringLiteral("qml/main.qml"));
viewer.showExpanded();
return app.exec();
}
qml/main.qml正是您问题中提供的片段
如果您使用QtCreator启动项目,您还将准备好使用qtquick2applicationviewer/文件夹。然后qmake && make && ./test
将启动应用程序。如果单击text元素,您将得到:
MyClass::MyClass()
void MyClass::doStuffFromQmlSlot()
https://askubuntu.com/questions/431368
复制相似问题