學(xué)習(xí)qml系列之一
說明:
學(xué)習(xí)qml系列之qwiget和qml信號槽的交互使用,并在qwidget中顯示qml界面
在qml中發(fā)送信號到qwidget里
在qwidget里發(fā)送信號給qml
在qwidget里面調(diào)用qml界面方式
方式一:使用QQuickView
這個是Qt5.0中提供的一個類,繼承自QQickWindow中,用來顯示qt quick用戶界面:
QQuickView *view = new QQuickView;
view->setSource(QUrl::fromLocalFile("main.qml"));
view->show();
QQuickView基于QWindow,需要轉(zhuǎn)換成 QWidget才能使用,還需要如下轉(zhuǎn)換
QQuickView *pView = new QQuickView();
QWidget *Widget = QWidget::createWindowContainer(pView, this);
pView->setResizeMode(QQuickView::SizeRootObjectToView);
pView->setSource(QUrl("qrc:/main.qml"));
這樣后面能直接調(diào)用由qml轉(zhuǎn)換成的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
// 發(fā)送給 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類
效果如下圖文章來源:http://www.zghlxwxcb.cn/news/detail-472452.html
文章來源地址http://www.zghlxwxcb.cn/news/detail-472452.html
到了這里,關(guān)于qml學(xué)習(xí)之qwidget與qml結(jié)合使用并調(diào)用信號槽交互的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!