1.在Qt-C++中调用qml的界面
Qt4
pro文件中加上 QT+=declarative
QDeclarativeView *view = new QDeclarativeView; view->setSource(QUrl::fromLocalFile("file.qml")); view->show();
Qt5
pro文件中加上 QT+=quickwidgets
QQuickWidget *view = new QQuickWidget; view->setSource(QUrl::fromLocalFile("file.qml")); view->show();
QDeclarativeView 与QQuickWidget 都继承自QWidget,可以当做QWidget处理,加入到其他容器或者QLayout中,即可在gui中显示qml的界面。
2.在qml中调用QWidget自定义控件
(1)自定义一个类,如MyWidget,继承于QQuickPaintedItem
#include <QQuickPaintedItem> class MyWidget: public QQuickPaintedItem { Q_OBJECT Q_PROPERTY(int mWidth READ getWidth WRITE setWidth)//可增加qml属性 Q_PROPERTY(int mHeight READ getHeight WRITE setHeight) public: MyWidget(QQuickItem *parent = 0); virtual ~MyWidget(); int getWidth() const; void setWidth(int w); int getHeight() const; void setHeight(int h); Q_INVOKABLE int doSomeThing();//可增加qml方法 protected: virtual void paint(QPainter *painter) override;//自绘控件 signals: void somethingHappend(const QString &msg); private: int m_Width; int m_Height; }
(2)然后注册qml类型
qmlRegisterType<MyWidget>("widget.test",1,0,"MyWidget");
(3)qml中调用
import QtQuick 2.9 import QtQuick.Window 2.2 import widget.test 1.0 Window { width: 500 height: 800 title: qsTr("QQuickPaintedItem test") MyWidget { id: testWidgetId anchor.fill: parent mWidth: parent.width mHeight: parent.height onSomethingHappend { console.log("getMsg: "+msg) } MouseArea { anchors.fill: parent onClicked: { testWidgetId.doSomeThing(); } } } }
最近留意到Qt Design Studio这个工具,可以直接从photshop导入,UI设计直接转换为qml。而qml界面又可以在C++中显示。这一套流程下来,感觉以后程序员都不用写界面了。恐怖如斯