在同一个项目中加载c++组件
main.qml
import QtQuick 2.15
import QtQuick.Controls 2.15
import QtQuick.Layouts 1.3
import org.test 1.0
ApplicationWindow {
visible: true
width: 400
height: 400
Log{
id: log
}
StackLayout {
id: stackLayout
anchors.fill: parent
Rectangle {
width: 200
height: 200
color: "red"
}
Rectangle {
width: 200
height: 200
color: "green"
}
Rectangle {
width: 200
height: 200
color: "blue"
}
}
Button {
text: "Next"
anchors.bottom: parent.bottom
anchors.horizontalCenter: parent.horizontalCenter
onClicked: {
log.add(2,4);
console.log("这是一条控制台信息",stackLayout.currentIndex);
stackLayout.currentIndex = (stackLayout.currentIndex + 1) % stackLayout.count
}
}
}
log.cpp
#ifndef LOG_H
#define LOG_H
#include <QQuickItem>
#include <QDebug>
#include <QObject>
#include <QQuickItem>
class Log : public QObject
{
public:
Log();
Q_OBJECT
//Q_DISABLE_COPY(Log)
Q_INVOKABLE int add(int a, int b){
//return a + b;
qDebug() << "zlb";
}
};
#endif // LOG_H
log.cpp
#include "log.h"
Log::Log() {}
main.cpp
#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include "log.h"
int main(int argc, char *argv[])
{
#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
#endif
QGuiApplication app(argc, argv);
QQmlApplicationEngine engine;
const QUrl url(QStringLiteral("qrc:/main.qml"));
qmlRegisterType<Log>("org.test", 1, 0, "Log");
QObject::connect(
&engine,
&QQmlApplicationEngine::objectCreated,
&app,
[url](QObject *obj, const QUrl &objUrl) {
if (!obj && url == objUrl)
QCoreApplication::exit(-1);
},
Qt::QueuedConnection);
engine.load(url);
return app.exec();
}