Important: Please read the Qt Code of Conduct -

Requesting model data from network

  • When in model methods rowCount() and columnCount() I try to retrieve data from server using QTcpSocket, the model calls these methods few times but not calls data() afterwards. The associated QTableView displays nothing. I checked with debugger and it shows that rowCount() and columnCount() are returning valid data.

    The model is derived from QAbstractTableModel. Here's the code of rowCount():

    //Setup waiting for server response
    QTimer timer;
    QEventLoop eventLoop;
    connect(&m_tcpSocket, &QTcpSocket::readyRead, &eventLoop, &QEventLoop::quit);
    connect(&timer, &QTimer::timeout, &eventLoop, &QEventLoop::quit);
    //Using QDataStream to send and receive model information
    QDataStream dataStream(&m_tcpSocket);
    dataStream << MSG_REQUEST_ROWS_COUNT;//Sending request for number of rows
    //If no response received
        connect(&m_tcpSocket, &QTcpSocket::readyRead, this, &TcpTableModel::readyRead);
        return 0;
    //Receiving information from server
    int msgType = -1;
    int rowCount = -1;
    dataStream >> msgType;
    dataStream >> rowCount;
    if((msgType != MSG_REQUEST_ROWS_COUNT) || (rowCount == -1))
        return 0;
    return rowCount;

    The server uses same approach to process the request. It receives MSG_REQUEST_ROWS_COUNT and then sends back MSG_REQUEST_ROWS_COUNT and an int containing the number of rows.

    What could be the source of such behavior in my program? Maybe QTableView can't work properly if its requests to model are satisfied with delay. Or maybe I should use completely different approach to get model data from server?

  • Lifetime Qt Champion


    From your description you seem to try to do some pseudo-synchronous handling while you data are technically retrieved asynchronously.

    You should rather implement an asynchronous model i.e. when you get new data like row/column count, then use the model notification mechanism to trigger the view's update.

Log in to reply