现象
使用 QTableWidget 时会发现,当外部代码去更新表中的数据,却发现界面没有自动更新。
即使在更新数据之后添加了ui->tableWidget->repaint();
或者ui->tableWidget->update()
,界面依然没有自动更新。
只有当鼠标点击界面时,数据才被刷新。
解决方法
使用如下代码:
ui->tableWidget->viewport()->update();
原因
update()
是更新这个控件
viewport()->update()
是更新这个控件里面的内容
进一步分析
QTableWidget Class 官网的资料如下
http://doc.qt.io/qt-5/qtablewidget.html
顺着继承关系,一步步往上找,会发现如下说明
Note: If you inherit QAbstractItemView and intend to update the contents of the viewport, you should use viewport->update() instead of update() as all painting operations take place on the viewport.



参考资料
[SOLVED] QTableWidget is not getting refreshed automatically
https://forum.qt.io/topic/10090/solved-qtablewidget-is-not-getting-refreshed-automatically
网友评论