赞
踩
这里是在Win10下,使用Qt5.7.0(cpp+qml)实现Qml嵌入Widget以及Qml与Widget交互。
QQuickWidget类,可以解决此问题。
QT += quickwidgets
main.cpp如下
- #include <QApplication>
- #include "qmlwidget.h"
- int main(int argc, char *argv[]) {
- QApplication app(argc, argv);
- QmlWidget qmlWidget;
- return app.exec();
- }
- #ifndef QMLWIDGET_H
- #define QMLWIDGET_H
- #include <QQuickWidget>
- #include <QQmlEngine>
- #include <QVBoxLayout>
- class QmlWidget : public QWidget
- {
- Q_OBJECT
- public:
- explicit QmlWidget(QWidget *parent = 0);
- private:
- QVBoxLayout * layout;
- QQuickWidget * quickWidget;
- signals:
- void sigWidget(void);
- public slots:
- void slotWidget(void);
- void btnClicked(void);
- };
- #endif // QMLWIDGET_H
- #include "qmlwidget.h"
- #include <QDebug>
- #include <QPushButton>
- QmlWidget::QmlWidget(QWidget *parent) : QWidget(parent) {
- quickWidget = new QQuickWidget();
- quickWidget->setSource(QUrl("qrc:///main.qml"));
- layout = new QVBoxLayout(this);
- QPushButton *btn1 = new QPushButton(this);
- btn1->setText("widget btn");
- layout->addWidget(btn1);
- connect(btn1,SIGNAL(clicked(bool)),this,SLOT(btnClicked()));
- QObject * obj = (QObject*)quickWidget->rootObject();
- connect(obj,SIGNAL(qmlClicked()),this,SLOT(slotWidget()));
- connect(this,SIGNAL(sigWidget()),obj,SIGNAL(widgetClicked()));
- quickWidget->setLayout(layout);
- quickWidget->show();
- }
- void QmlWidget::slotWidget() {
- qDebug()<<"qml sig to widget slot";
- emit sigWidget();
- }
- void QmlWidget::btnClicked() {
- qDebug()<<"widget btn clicked";
- }
- import QtQuick 2.4
- import QtQuick.Layouts 1.2
- import QtQuick.Controls 1.4
- import QtQuick.Dialogs 1.2
- Rectangle {
- id : root;
- width: 300
- height: 300
- color: "yellow"
- signal qmlClicked()
- signal widgetClicked()
- onWidgetClicked: {
- console.log("widget sig to qml slot")
- }
- Button {
- id : qmlBtn
- anchors.top: parent.top
- text : "qml btn"
- onClicked: {
- console.log("qml btn clicked")
- }
- }
- Button {
- anchors.left: qmlBtn.right
- anchors.leftMargin: 8
- text : "connect btn"
- onClicked: {
- qmlClicked()
- }
- }
- }
quickWidget的rootObject()是main.qml中的根对象,也就是root,它要转换为QObject*类型才能使用connect。
quickWidget不能直接连接到qml的槽上,但是可以连接到qml的信号上,让信号去触发qml的槽。
本文福利,莬费领取Qt开发学习资料包、技术视频,内容包括(Qt实战项目,C++语言基础,C++设计模式,Qt编程入门,QT信号与槽机制,QT界面开发-图像绘制,QT网络,QT数据库编程,QT项目实战,QSS,OpenCV,Quick模块,面试题等等)↓↓↓↓↓↓见下面↓↓文章底部点击莬费领取↓↓
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。