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; timer.setSingleShot(true); QEventLoop eventLoop; connect(&m_tcpSocket, &QTcpSocket::readyRead, &eventLoop, &QEventLoop::quit); connect(&timer, &QTimer::timeout, &eventLoop, &QEventLoop::quit); timer.start(TIMEOUT); //Using QDataStream to send and receive model information QDataStream dataStream(&m_tcpSocket); dataStream << MSG_REQUEST_ROWS_COUNT;//Sending request for number of rows eventLoop.exec(); //If no response received if(!timer.isActive()) { connect(&m_tcpSocket, &QTcpSocket::readyRead, this, &TcpTableModel::readyRead); return 0; } timer.stop(); //Receiving information from server dataStream.startTransaction(); int msgType = -1; int rowCount = -1; dataStream >> msgType; dataStream >> rowCount; if((msgType != MSG_REQUEST_ROWS_COUNT) || (rowCount == -1)) { dataStream.commitTransaction(); return 0; } dataStream.commitTransaction(); 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?
-
Hi,
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.