Qt Widget项目中插入qml页面并链接信号槽

 

如果是QtCreatord,首先在.pro文件中,加入QT+=quickwidgets,QQuickWidget可以将qml文件转化成QWidget的子类,这样就可以放进Qt Widget控件的layout中了。

 

在vs中这样设置即可

 

test.qml

import QtQuick 2.9
import QtQuick.Window 2.2

Rectangle
{
    id: root
    color: "red"
    width: 500
    height: 500

    signal qmlSignal
    signal cSignal

    Text
    {
        id: text
        text: qsTr("Test")
        font.pointSize: 20
        anchors.centerIn: parent
    }

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

    onCSignal: {
        root.color = "green"
        text.text = "test successful!"
    }
}

widget.cpp

#include "widget.h"
#include "ui_widget.h"
#include <QGuiApplication>
#include <QQuickWidget>
#include <QHBoxLayout>

Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);

    QQuickWidget *view = new QQuickWidget;
    view->setSource(QUrl::fromLocalFile("D://Test//QTCreatorTest//test.qml"));
    view->show();

    this->layout()->addWidget(view);

    connect(ui->pushButton, SIGNAL(clicked(bool)), (QObject*)view->rootObject(), SIGNAL(cSignal()));
}

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

 

 

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