I am trying to implement Reading and writing files in QML and came across the linked article from Nokia but have not been able to successfully use the seemingly obvious code
The example written by Nokia in the tutorial is not a pure QML program. It contains both C++ and QML. This kind of program is usually a C++ program which loads a QML file and renders it. C++ programs usually begin with a function called int main(int argc, char *argv[]);
. In your case, it is this "main()" function which loads your QML main file (main.qml
) file and renders it.
But before loading the QML main file, you have to tell the QML system that you will use a custom QML class called FileIO
. For this, you will have to use the int qmlRegisterType
C++ function. It takes about 5 parameters :
For using this function, you have to include a C++ header in the C++ file where you write it :
.
.In the end you should have some stuff like this :
main.cpp (file with the main() C++ function) :
// C++ header to include for using qmlRegisterType();
#include // If you use Qt4
#include // If you use Qt5
// Some stuff used by the main(); function
#include
#include
#include "ui/qtquickapplicationviewer.hpp" // Something which manages your QML files. Qt Creator will generate it for you if you use it to code..
#include "fileio.h" // Your FileIO C++ class
/**
* @fn Q_DECL_EXPORT int main(int argc, char *argv[])
* @brief The C++ main(); function. Your program begins HERE.
*/
Q_DECL_EXPORT int main(int argc, char *argv[])
{
QApplication app(argc, argv);
// ...
// Declaring your C++ class to the QML system
qmlRegisterType("MyCustomClasses", 1, 0, "FileIOQML");
// ...
// Loading your main QML file
QLatin1String mainQMLFile = "./ui/qml/main.qml";
QtQuickApplicationViewer viewer;
viewer.setMainQmlFile(mainQMLFile);
// Showing how beautiful your QML interface is :)
viewer.showExpanded();
// Now let's play with your QML interface is :)
return app.exec();
}
main.qml file to load (right from the Nokia tutorial) :
import QtQuick 1.1
import MyCustomClasses 1.0
Rectangle {
width: 360
height: 360
Text {
id: myText
text: "Hello World"
anchors.centerIn: parent
}
FileIOQML {
id: myFile
source: "my_file.txt"
onError: console.log(msg)
}
Component.onCompleted: {
console.log( "WRITE"+ myFile.write("TEST"));
myText.text = myFile.read();
}
}
NB : I have changed some "FileIO" from the Nokia tutorial in order to avoid confusions.