QML自定义信号和C++槽函数连接

0x00 在QML中创建CheckBox控件是否勾选的自定义信号

import QtQuick 2.14
import QtQuick.Window 2.14
import QtQuick.Controls 2.12
import QtQuick.Layouts 1.12

Window {
    visible: true
    width: 640
    height: 480
    title: qsTr("Qml调用C++")

    Column{
        anchors.fill: parent;
        anchors.margins: 20;

        CheckBox{
            objectName: "hldCheckBox";
            id: checkBox;
            text: "enable";

            // CheckBox控件的自定义信号
            signal enable_sig(bool value);

            onClicked: {
                if(checkBox.checked){
                    enable_sig(true);
                    console.log("Enable");
                }
                else{
                    enable_sig(false);
                    console.log("Disable");
                }
            }
        }
    }
}

0x01 创建一个C++类,并定义槽函数

#ifndef MIDDLECOMM_H
#define MIDDLECOMM_H

#include 

class MiddleComm : public QObject
{
    Q_OBJECT
public:
    explicit MiddleComm(QObject *parent = nullptr);

signals:

public slots:
    void enable_slot(bool enable);

};

#endif // MIDDLECOMM_H

#include "middlecomm.h"
#include 

MiddleComm::MiddleComm(QObject *parent) : QObject(parent)
{

}

void MiddleComm::enable_slot(bool enable)
{
    if(enable){
        qDebug() << "CheckBox checked";
    }
    else{
        qDebug() << "CheckBox not checked";
    }
}

0x02 在main.cpp中MiddleComm类的槽函数和CheckBox控件的自定义信号建立连接

#include 
#include 
#include 
#include "middlecomm.h"

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

    QGuiApplication app(argc, argv);

    QQmlApplicationEngine engine;
    const QUrl url(QStringLiteral("qrc:/main.qml"));
    QObject::connect(&engine, &QQmlApplicationEngine::objectCreated,
                     &app, [url](QObject *obj, const QUrl &objUrl) {
        if (!obj && url == objUrl)
            QCoreApplication::exit(-1);
    }, Qt::QueuedConnection);
    engine.load(url);

    auto root = engine.rootObjects();
    // 获取指定的CheckBox对象
    auto checkBox = root.first()->findChild<QObject*>("hldCheckBox");

    MiddleComm middleComm;
    QObject::connect(checkBox, SIGNAL(enable_sig(bool)), &middleComm, SLOT(enable_slot(bool)));

    return app.exec();
}

你可能感兴趣的:(QML,c++,qml)