I think that when you first read model->rowCount() , the model did not fully take all the results. Although it will be displayed later when the table view is displayed, which will lead to the full display of the rows in the table view.
Try using QSqlQueryModel::fetchMore before reading the row counter:
while (model->canFetchMore()) model->fetchMore(); int rows=model->rowCount(); int columns=model->columnCount();
[Additional Information from Tay2510]:
You can simply change the file open flag
if(csvfile.open(QIODevice::WriteOnly|QIODevice::Truncate))
to
if(csvfile.open(QIODevice::WriteOnly))
The former will overwrite the same file, while the latter will add data to it.
source share