gpt4 book ai didi

c++ - QML和C++连接信号

转载 作者:行者123 更新时间:2023-11-30 05:13:41 24 4
gpt4 key购买 nike

我想将 QML 信号连接到 C++ 函数。我真的不明白我怎样才能得到正确的项目。现在我用下面的方法尝试它,这是行不通的(还有,会有更简单的方法吗?),这是我试过的代码:

主要.cpp:

#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include "include/myclass.h"

int main(int argc, char *argv[])
{
QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
QGuiApplication app(argc, argv);

QQmlApplicationEngine engine;
engine.load(QUrl(QLatin1String("qrc:/main.qml")));

QQmlComponent component(&engine, "qrc:/Page1.qml");
QObject *item = component.create();
MyClass myClass;
QObject::connect(item, SIGNAL(testSignal()),&myClass,SLOT(cppSlot()));

return app.exec();
}

主.qml:

import QtQuick 2.7
import QtQuick.Controls 2.0
import QtQuick.Layouts 1.0

ApplicationWindow {
visible: true
width: 800
height: 460

Page1 {
id: page1
visible: true
}
}

Page1.qml:

import QtQuick 2.7
import QtQuick.Window 2.2

Item {
width: 800
height: 460

signal testSignal()

CustomButton {
id: cppSignalButton
x: 14
y: 55
buttonText: "Test CPP Signal"
onButtonClicked: {
testSignal();
}
}
}

自定义按钮.qml:

import QtQuick 2.7
import QtQuick.Window 2.2


Rectangle {
id: root
width: 200
height: 50
color: "#000000"
border.color: "#FFFFFF"

property string buttonText
signal buttonClicked()

MouseArea {
id: mouseArea
anchors.fill: parent

onClicked:{
root.buttonClicked();
}

}
Text {
id: text1
x: 105
y: 31
color: "#ffffff"
text: buttonText
anchors.verticalCenter: parent.verticalCenter
anchors.horizontalCenter: parent.horizontalCenter
font.pixelSize: 20
}
}

和 myclass.cpp:

#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <iostream>
#include <fstream>
#include <QQuickItem>
#include <QQuickView>

class MyClass : public QObject
{
Q_OBJECT
public:
MyClass(){

};
public slots:
void cppSlot() {
std::ofstream textfile;
textfile.open("test.txt");
textfile << "Signal worked" << std::endl;
textfile.close();
qInfo( "Called the C++ slot" );
}
};

最佳答案

首先你应该阅读这篇文章:Integrating QML and C++

您可以通过以下方式从 qml 调用您的 MyClass 对象方法:

// main.cpp

#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>
#include "include/myclass.h"

int main(int argc, char *argv[])
{
QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
QGuiApplication app(argc, argv);

QQmlApplicationEngine engine;
MyClass myClass;
engine.rootContext()->setContextProperty("myClass", &myClass);
engine.load(QUrl(QLatin1String("qrc:/main.qml")));



return app.exec();
}

//Page1.qml

import QtQuick 2.7
import QtQuick.Window 2.2

Item {
width: 800
height: 460

signal testSignal()

CustomButton {
id: cppSignalButton
x: 14
y: 55
buttonText: "Test CPP Signal"
onButtonClicked: {
myClass.cppSlot(); //now you can use the context property to invoke your slot
}
}
}

关于c++ - QML和C++连接信号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43822547/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com