这里是在Win10下,使用Qt5.7.0(cpp+qml)实现Qml嵌入Widget以及Qml与Widget交互。
QQuickWidget类,可以解决此问题。
1、先在pro是加入
QT += quickwidgets
2、新建QmlWidget类,并继承QWidget。
main.cpp如下
#include <QApplication>
#include "qmlwidget.h"
int main(int argc, char *argv[]) {
QApplication app(argc, argv);
QmlWidget qmlWidget;
return app.exec();
}
3、qmlwidget.h如下
#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
4、qmlwidget.cpp如下
#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";
}
5、main.qml如下
import QtQuick 2.4
import QtQuick.Layouts 1.2
import QtQuick.Controls 1.4
import QtQuick.Dialogs 1.2
Rectangle {
id : root;
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()
}
}
}
6、运行效果如下
7、注意事项。
quickWidget的rootObject()是main.qml中的根对象,也就是root,它要转换为QObject*类型才能使用connect。
quickWidget不能直接连接到qml的槽上,但是可以连接到qml的信号上,让信号去触发qml的槽。