第二卷如何更快速的放弃,注重的是C++和QML的交互
<1>记事本。。
(1) 先测试下不在QML创建C++对象,仅仅在main.cpp添加一个属性函数供调用.
TextStreamLoader.h
#ifndef TEXTSTREAMLOADER_H #define TEXTSTREAMLOADER_H #include <QObject> #include <QTextStream> #include <QDebug> class TextStreamLoader : public QObject { Q_OBJECT public: explicit TextStreamLoader(QObject *parent = 0); signals: void signal_readFile(QString file); void signal_error(QString errorMsg); public slots: void slot_readFile(QString file); void slot_saveFile(QString file,QString buffer); void slot_test(){qDebug() << "test C++";} }; #endif // TEXTSTREAMLOADER_H
TextStreamLoader.cpp
#include "TextStreamLoader.h" #include <QFile> TextStreamLoader::TextStreamLoader(QObject *parent) : QObject(parent) { qDebug() << "Construct the TextStreamLoader"; } void TextStreamLoader::slot_readFile(QString file) { QFile rfile(file); if(!rfile.open(QIODevice::ReadOnly)) { QString errorMsg = "Could not open " + file + "\n"; emit signal_error(errorMsg); return ; } QTextStream in(&rfile); QString data = in.readAll(); emit signal_readFile(data); rfile.close(); } void TextStreamLoader::slot_saveFile(QString file, QString buffer) { QFile wfile(file); if(!wfile.open(QFile::WriteOnly)) { QString errorMsg = "Could not open " + file + "\n"; emit signal_error(errorMsg); return ; } QTextStream out(&wfile); out >> buffer; wfile.close(); }
main.cpp
#include <QGuiApplication> #include <QQmlApplicationEngine> #include <QQmlContext> #include "TextStreamLoader.h" int main(int argc, char *argv[]) { QGuiApplication app(argc, argv); QQmlApplicationEngine engine; QQmlContext *context = engine.rootContext(); // 注意对象是在C++里构建 TextStreamLoader stream_01; context->setContextProperty("stream_01",&stream_01); // 构建完C++对象 // 加载我们的QML界面,只能调用槽函数 qDebug() << "load the main.qml"; engine.load(QUrl(QStringLiteral("qrc:/main.qml"))); qDebug() <<engine.rootObjects()[0]->objectName(); // this will be debug "Houdini" return app.exec(); }
main.qml 用最简单的测试下我们的TextStreamLoader 里面的 "test()槽函数",一定要是槽函数才能被调用
import QtQuick 2.6 import QtQuick.Window 2.2 Window { objectName: "Houdini" visible: true width: 640 height: 480 title: qsTr("Hello World") MouseArea { anchors.fill: parent onClicked: stream_01.slot_test(); // 并没有构建对象,因为在main.cpp构建的 } }
时间: 2024-10-10 16:07:25