qml与c++混合编程之简单demo说明

最近接触QML,感觉非常kuo,demo中实现一个按键,名为Open,功能就是打开文件,很简单。打开过程是c++干事,界面是QML写的。

qml与c++混合编程不清楚的,可以看我前面一篇文档。

file.h

#ifndef FILE_H
#define FILE_H
#include 
class test_file: public QObject
{
    Q_OBJECT
public:
    explicit test_file(QObject *parent = 0);
signals:
    void someSignal();
public slots:
    void on_actionOpen_triggered(); // 打开文件菜单
 
  
};
 
  
#endif // FILE_H
on_actionOpen_triggered();是槽函数,还得有个signals函数;

file.cpp

 
  
#include "file.h"
#include "QDebug"
#include 
test_file::test_file(QObject *parent):
    QObject(parent)
{
 
  
}

void test_file::on_actionOpen_triggered()// 打开文件菜单
{
    QString fileName = QFileDialog::getOpenFileName(); // 获取文件路径
    emit someSignal();
    qDebug()< 
  
}
 main.cpp 
  

#include "mainwindow.h"
#include 
#include 
#include 
#include 
#include 
#include "file.h"
int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
 
  
    QQmlApplicationEngine engine;
    test_file f;
    engine.load(QUrl(QStringLiteral("qrc:/edit/main.qml")));
    engine.load(QUrl(QStringLiteral("qrc:/edit/Buttons.qml")));
    engine.rootContext()->setContextProperty("FILE_USER",&f);
 
  
    return a.exec();
}

main.qml

import QtQuick 2.0
import QtQuick.Controls 1.1
 
  
ApplicationWindow {
    id: aw
    visible: true
    width: 900
    height: 900
    title: qsTr("edit")
Rectangle {
    width: 600
    height: 600
    color: "#609ca0"
    Rectangle{//按钮
        x:50;y:40
        Buttons{
            anchors.horizontalCenter: parent.horizontalCenter
            text: "Open"
             onClick.onClicked:FILE_USER.on_actionOpen_triggered()
        }
    }
  }
}
 
  

Buttons.qml

import QtQuick 2.0
Rectangle {
    id:button_type
    property alias onClick:ma
    property alias text: textElement.text;
 
  
    width: 90; height: 40
    border.color: "steelblue";border.width:2
    radius: 8
 
  
    Text {
        id: textElement
        anchors.centerIn: parent
        font.pointSize: 25
        style: Text.Raised; 
    }
    MouseArea{
        id: ma
        anchors.fill: parent
	}
}
 
  

运行结果如下:


点击Open的时候,弹出如下弹框选择:


你可能感兴趣的:(QT)