c++qtqtcpsocketqabstracttablemodelqdatastream

How to send QSqlQueryModel over QTcpSocket with QDatastream?


I want to send QSqlQueryModel to the another client with QDatastream and QTcpSocket. I want to remove some rows and add few extra rows to QSqlQueryModel (without changing the database) and send it to the client like this pseudocode:-

QTcpSocket socket;
socket.setSocketDescriptor(handle);
socket.waitForReadyRead(WAIT_TIME);

QByteArray req = socket->readAll();
QDataStream reqstream(&req,QIODevice::ReadOnly);

QSqlQueryModel MyModel;
....
// fetch data with MyModel
// add/remove some rows from that model without adding/removing them from actual database
....

QByteArray res;
QDataStream resstream(&res,QIODevice::WriteOnly);
resstrem << MyModel;
socket.write(res);

How can I achieve this without creating new deep copy of Model. On the client side, it should only receive a model with data so I can show it in QML.


Solution

  • The purpose of any descendant of QAbstractItemModel is to adopt some data to views (widgets) which can present them.

    So basically you are trying do something what is outside of design of this class. Its like trying to hit the nail with a shovel. It is possible, but dangerous and not recommended.

    Just read debase data using QSqlQuery (use hammer) iterate over a rows read columns and store them in some serialization format. You can use QDataStream for that:

        QDataStream out{&socket};
    
        QSqlQuery query{"SELECT country FROM artist"};
        while (query.next()) {
            out << query.value(0).toString();
        }
    

    It is possible to make this asynchronous.