Search code examples
c++qtconstructorstreamwriterqtxml

How to initialize QXmlStreamWriter with QString as member variable?


I have implemented my own xml writer to generate xml as QString.

i have create a class "MyXmlWriter" with private member variable as QXmlStreamWriter and try to initialize it in the public method writeToString()

in declaration header file:

class MyXmlWriter {
  public:
    MyXmlWriter();
    ~MyXmlWriter();
    QString writeToString();
  private:
    QXmlStreamWriter writer;
    void writePart();
}

in cpp file:

void MyXmlWriter::writePart() {
   // i want to use the QXmlStreamWriter instance hier
}
QString MyXmlWriter::writeToString(){
   QString result;
   writer(&result); // at this became the error: no match for call to '(QXmlStreamWriter) (QString*)'
   xmlWriter.setAutoFormatting(true);
   // private method called 
   writePart();

   return result;
}

this error appear on build: error: no match for call to (QXmlStreamWriter) (QString) writer(&result); *

If the QXmlStreamWriter write is declared in the local method writeToString() then i cant access this writer in private method writePart() i want to use the member variable "writer" in other methods that's why a local declaration isn't an option for me.


Solution

  • You have to assign a new object to your variable writer, like this:

    QString MyXmlWriter::writeToString() {
        QString result;
        writer = QXmlStreamWriter(&result);  // will not compile
        return result;
    }
    

    This code is dangerous. result is destroyed at the end of writeToString(), so writer then contains invalid data and you cannot use it anymore.

    Additionally, QXmlStreamWriter cannot be copied, so this would probably not compile at all. It's better to just pass the QXmlStreamWriter to your methods, like this:

    class MyXmlWriter {
      public:
        MyXmlWriter();
        ~MyXmlWriter();
        QString writeToString();
      private:
        void writePart(QXmlStreamWriter &writer);
    }
    

    and

    QString MyXmlWriter::writeToString() {
        QString result;
        QXmlStreamWriter writer(&result);
    
        writePart(writer);
        writePart(writer);
    
        return result;
    }