使用 Qt 5.4.0 和 Qt Creator 3.3.0,创建新项目:
- 点击新建项目
- Qt 快速应用程序
- 点击选择...
- 为项目命名并选择放置位置
- 点击下一步
- 从下拉菜单中选择 Qt Quick 2.4
- 点击下一步
- 选择所需的套件
- 点击下一步
- 点击完成
现在您应该看到带有以下代码的打开的 main.qml 文件:
import QtQuick 2.4
import QtQuick.Window 2.2
Window {
visible: true
MainForm {
anchors.fill: parent
mouseArea.onClicked: {
Qt.quit();
}
}
}
对文件进行更改,使其如下所示:
import QtQuick 2.4
import QtQuick.Window 2.2
Window {
visible: true
//### New Code ###
signal myQmlSignal(string msg)
//################
MainForm {
anchors.fill: parent
mouseArea.onClicked: {
//### New Code ###
//Replace "Qt.quit();" with
console.log("Sending myQmlSignal from QML...");
myQmlSignal("Hello from QML")
//################
}
}
}
将新类添加到您的项目:
- 在项目查看器中右键单击项目名称
- 单击添加新...
- 如果尚未选择,请选择 C++ 类
- 点击选择...
- 在 Class name 字段中输入“MyCppClass”
- 将基类设置为 QObject
- 点击下一步
- 点击完成
打开 mycppclass.h 文件,它应该如下所示:
#ifndef MYCPPCLASS_H
#define MYCPPCLASS_H
#include <QObject>
class MyCppClass : public QObject
{
Q_OBJECT
public:
explicit MyCppClass(QObject *parent = 0);
~MyCppClass();
signals:
public slots:
};
#endif // MYCPPCLASS_H
对 mycppclass.h 进行更改,使其如下所示:
#ifndef MYCPPCLASS_H
#define MYCPPCLASS_H
#include <QObject>
//### New Code ###
#include <QDebug>
//################
class MyCppClass : public QObject
{
Q_OBJECT
public:
explicit MyCppClass(QObject *parent = 0);
~MyCppClass();
signals:
public slots:
//### New Code ###
void myCppSlot(const QString &msg);
//################
};
#endif // MYCPPCLASS_H
打开 mycppclass.cpp,它应该如下所示:
#include "mycppclass.h"
MyCppClass::MyCppClass(QObject *parent) : QObject(parent)
{
}
MyCppClass::~MyCppClass()
{
}
将其更改为:
#include "mycppclass.h"
MyCppClass::MyCppClass(QObject *parent) : QObject(parent)
{
}
MyCppClass::~MyCppClass()
{
}
void MyCppClass::myCppSlot(const QString &msg)
{
//### New Code ###
qDebug() << "Signal was received by C++. It contains follwoing message: " << msg;
//################
}
打开 main.cpp,如下所示:
#include <QGuiApplication>
#include <QQmlApplicationEngine>
int main(int argc, char *argv[])
{
QGuiApplication app(argc, argv);
QQmlApplicationEngine engine;
engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
return app.exec();
}
并进行以下更改:
#include <QGuiApplication>
#include <QQmlApplicationEngine>
//### New Code ###
#include "mycppclass.h"
//################
int main(int argc, char *argv[])
{
QGuiApplication app(argc, argv);
QQmlApplicationEngine engine;
engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
//### New Code ###
MyCppClass myCppClass;
QObject::connect(engine.rootObjects().takeFirst(), SIGNAL(myQmlSignal(QString)), &myCppClass, SLOT(myCppSlot(QString)));
//################
return app.exec();
}
单击绿色大三角形编译并运行您的应用程序。观看应用程序输出区域,单击 Hello World,您应该会看到打印出以下消息:
qml:从 QML 发送 myQmlSignal...
信号被 C++ 接收。它包含以下消息:“来自 QML 的你好”