FileIO Implementation

Remember the FileIO API we want to create should look like this.

  1. class FileIO : public QObject {
  2. ...
  3. Q_PROPERTY(QUrl source READ source WRITE setSource NOTIFY sourceChanged)
  4. Q_PROPERTY(QString text READ text WRITE setText NOTIFY textChanged)
  5. ...
  6. public:
  7. Q_INVOKABLE void read();
  8. Q_INVOKABLE void write();
  9. ...
  10. }

We will leave out the properties, as they are simple setters and getters.

The read method opens a file in reading mode and reads the data using a text stream.

  1. void FileIO::read()
  2. {
  3. if(m_source.isEmpty()) {
  4. return;
  5. }
  6. QFile file(m_source.toLocalFile());
  7. if(!file.exists()) {
  8. qWarning() << "Does not exist: " << m_source.toLocalFile();
  9. return;
  10. }
  11. if(file.open(QIODevice::ReadOnly)) {
  12. QTextStream stream(&file);
  13. m_text = stream.readAll();
  14. emit textChanged(m_text);
  15. }
  16. }

When the text is changed it is necessary to inform others about the change using emit textChanged(m_text). Otherwise, property binding will not work.

The write method does the same but opens the file in write mode and uses the stream to write the contents of the text property.

  1. void FileIO::read()
  2. {
  3. if(m_source.isEmpty()) {
  4. return;
  5. }
  6. QFile file(m_source.toLocalFile());
  7. if(!file.exists()) {
  8. qWarning() << "Does not exist: " << m_source.toLocalFile();
  9. return;
  10. }
  11. if(file.open(QIODevice::ReadOnly)) {
  12. QTextStream stream(&file);
  13. m_text = stream.readAll();
  14. emit textChanged(m_text);
  15. }
  16. }

To make the type visible to QML, we add the QML_ELEMENT macro just after the Q_PROPERTY lines. This tells Qt that the type should be made available to QML. If you want to provide a different name than the C++ class, you can use the QML_NAMED_ELEMENT macro.

TODO TODO TODO

Do not forget to call make install at the end. Otherwise, your plugin files will not be copied over to the qml folder and the qml engine will not be able to locate the module.

TODO TODO TODO

TIP

As the reading and writing are blocking function calls you should only use this FileIO for small texts, otherwise, you will block the UI thread of Qt. Be warned!