C++与QML信号交互(非Q_PROPERTY法)

运行截图如下:

源码如下:

widget.h

#ifndef WIDGET_H
#define WIDGET_H

#include <QWidget>

namespace Ui {
class Widget;
}

class Widget : public QWidget
{
    Q_OBJECT

public:
    explicit Widget(QWidget *parent = 0);
    ~Widget();

signals:
    void sendMsg();

public slots:
    void qmlSlot();

private:
    Ui::Widget *ui;
};

#endif // WIDGET_H

main.cpp

#include "widget.h"
#include <QApplication>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    Widget w;
    w.show();

    return a.exec();
}

widget.cpp

#include "widget.h"
#include "ui_widget.h"
#include <QUrl>
#include <QMetaObject>
#include <QDebug>
#include <QMetaObject>

Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);
    ui->quickWidget->setSource(QUrl("qrc:/test.qml"));

    QObject *pRoot = (QObject*)ui->quickWidget->rootObject();

    Q_ASSERT(pRoot);

    connect(pRoot, SIGNAL(qmlSignal()), this, SLOT(qmlSlot()));
    connect(ui->pushButton, SIGNAL(clicked(bool)), pRoot, SIGNAL(cSignal()));

    const QMetaObject *metaObject=pRoot->metaObject();

    const QMetaObject *thisObject=this->metaObject();
}

Widget::~Widget()
{
    delete ui;
}

void Widget::qmlSlot()
{
    ui->pushButton->setText("qmlSlot called!");
}

test.qml

import QtQuick 2.0

Rectangle {

    id: root
    color: "green"

    Text {
        id: myText
        text: qsTr("hello")
        font.pixelSize: 70
        color: "red"
        anchors.centerIn: parent
    }

    signal qmlSignal
    signal cSignal

    MouseArea {
        anchors.fill: parent
        onClicked: qmlSignal()
    }

    onCSignal: {
        root.color = "yellow"
        myText.text = "how are you?"
    }
}

 

©️2020 CSDN 皮肤主题: 数字20 设计师:CSDN官方博客 返回首页