赞
踩
学习qml系列之一
说明:
学习qml系列之qwiget和qml信号槽的交互使用,并在qwidget中显示qml界面
在qml中发送信号到qwidget里
在qwidget里发送信号给qml
方式一:使用QQuickView
这个是Qt5.0中提供的一个类,继承自QQickWindow中,用来显示qt quick用户界面:
QQuickView *view = new QQuickView;
view->setSource(QUrl::fromLocalFile("main.qml"));
view->show();
QQuickView基于QWindow,需要转换成 QWidget才能使用,还需要如下转换
QQuickView *pView = new QQuickView();
QWidget *Widget = QWidget::createWindowContainer(pView, this);
pView->setResizeMode(QQuickView::SizeRootObjectToView);
pView->setSource(QUrl("qrc:/main.qml"));
这样后面能直接调用由qml转换成的QWidget界面了。
方式二:使用QQuickWidget
QQuickWidget *pWidget = new QQuickWidget();
pWidget->setResizeMode(QQuickWidget::SizeRootObjectToView);
pWidget->setSource(QUrl("qrc:/main.qml"));
该方法在Qt5.3中提供的一个类,继承自QWidget,是QQuickWidget一个很方便的包装器,用于显示Qt Quick用户界面
源码:
qml文件源码:
import QtQuick 2.1 Rectangle { id: root color: "green" width: 200 height: 200 // 发送给 Qt Widgets 的信号 signal qmlSignal // 从 Qt Widgets 接收到的信号 signal cSignal//信号的名称不能以大写开头 Text { id: myText text: "Click me" font.pointSize: 14 anchors.centerIn: parent } MouseArea { anchors.fill: parent onClicked: qmlSignal() } // 信号处理程序(处理从 Qt Widgets 接收到的信号) onCSignal: { root.color = "blue" myText.text = "Call the qml signal handler" } }
注意:qml中信号的名称不能以大写开头,然后添加到Qt的资源文件中
添加qml quick
QT += core gui qml quick
#include "widget.h" #include "ui_widget.h" #include "widget.h" #include <QQuickView> #include <QVBoxLayout> //#include <QQuickWidget> Widget::Widget(QWidget *parent) : QWidget(parent) , ui(new Ui::Widget) { // ui->setupUi(this); resize(300, 300); // 方式一 QQuickView *pView = new QQuickView(); QWidget *pWidget = QWidget::createWindowContainer(pView, this); pView->setResizeMode(QQuickView::SizeRootObjectToView); pView->setSource(QUrl("qrc:/main.qml")); // 方式二 // QQuickWidget *pWidget = new QQuickWidget(); // pWidget->setResizeMode(QQuickWidget::SizeRootObjectToView); // pWidget->setSource(QUrl("qrc:/main.qml")); m_pButton = new QPushButton(this); m_pButton->setText("Qt Widgets..."); QVBoxLayout *pLayout = new QVBoxLayout(); pLayout->addWidget(pWidget); pLayout->addWidget(m_pButton); pLayout->setSpacing(10); pLayout->setContentsMargins(10, 10, 10, 10); setLayout(pLayout); // QML 与 Qt Widgets 通信 QObject *pRoot = (QObject*)pView->rootObject(); // QObject *pRoot = (QObject*)pWidget->rootObject(); if (pRoot != NULL) { connect(pRoot, SIGNAL(qmlSignal()), this, SLOT(receiveFromQml())); connect(m_pButton, SIGNAL(clicked(bool)), pRoot, SIGNAL(cSignal())); } } Widget::~Widget() { delete ui; } void Widget::receiveFromQml() { m_pButton->setText("Call the C++ slot"); }
由于我使用的版本时5.14.1版本,用的QQuickView类
效果如下图
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。