赞
踩
qt调用qml文件的方式还是有多种,但是我习惯运用QQmlApplicationEngine来加载qml文件,因为这个类还可以吧qt类注册到qml中调用,这样交互非常方便。
比如:
QQmlApplicationEngine m_engin.load(QUrl(QStringLiteral("qrc:/qml/main.qml")));
这样就可以把qml文件加载出来
QQmlApplicationEngine m_engin.rootContext()->setContextProperty("QMLInteractObj", this);
这个是把qt QObject类注册到qml中提供调用,这样在qml文件可以任意调用qt函数,qt函数需要调用需要添加Q_INVOKABLE ,比如qt函数:
public slots:
Q_INVOKABLE void showname(QString name);
此函数用Q_INVOKABLE 了,在qml文件就可以直接调用,qml调用函数方式:
MouseArea{
onClicked: {
QMLInteractObj.showname(showname.text)
}
}
main.qml
import QtQuick 2.12 import QtQuick.Window 2.12 import QtQuick.Controls 1.4 import QtQuick.Controls.Styles 1.4 Window { id:mainwindow visible: true width: 600 //Screen.width height: 480 //Screen.height+1 //嵌入防止闪屏 高度必须加1 //flags: Qt.Window | Qt.FramelessWindowHint title: qsTr("This is qml Window") color: "#ffffff" objectName: "mainwindowobj" Rectangle{ z:111 width: parent.width/2 height: parent.height color: "#999999" focus: true Text { font.family: "微软雅黑" font.pointSize: 12 x:10 y:10 color: "white" text: qsTr("这是qml窗口") } TextField{ id:showname width: 200 height: 50 anchors.centerIn: parent placeholderText:"请输入名字" font.family: "宋体" font.pointSize: 14 textColor:"black" text:"" // validator: IntValidator {bottom: 1000; top: 99999;} //focus: true style: TextFieldStyle { placeholderTextColor:"black" background: Rectangle { implicitWidth: 300 implicitHeight: 50 border.width: 1 border.color: "#ffffff" } } } Button{ text: "发送" width: 50 height: 50 anchors.bottom: parent.bottom anchors.horizontalCenter: parent.horizontalCenter onClicked: { if(showname.text != "") { QMLInteractObj.showname(showname.text) } } } } Component.onCompleted: { //初始化设置qwiget窗口大小 QMLInteractObj.setwindowRect(mainwindow.width/2,0,mainwindow.width/2,mainwindow.height) } Connections{ //接收c++类发送的信号处理 可传参数 target: QMLInteractObj onPutqmlinfo:{ showname.text=qtname } } Connections{ target: mainwindow onClosing: { //可处理程序退出前要做的事情 可添加提示 console.log("我要退出了!!!!") } } function showname(name){ showname.text=name } }
初始化以及嵌入qml代码:
m_engin.rootContext()->setContextProperty("QMLInteractObj", this);
m_engin.load(QUrl(QStringLiteral("qrc:/qml/main.qml")));
if (m_engin.rootObjects().isEmpty())
{
return false;
}
QObject* obj = m_engin.rootObjects().at(0);
basewindowobj.setWndBaseInfo(obj);
basewindowobj.setWndSplitType();
项目效果图:
此项目对初学者是个不错的选择,可加QQ交流1174158241
完整项目下载地址:
下载地址
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。