現(xiàn)象
使用 QTableWidget 時(shí)會(huì)發(fā)現(xiàn)花竞,當(dāng)外部代碼去更新表中的數(shù)據(jù),卻發(fā)現(xiàn)界面沒有自動(dòng)更新矾柜。
即使在更新數(shù)據(jù)之后添加了ui->tableWidget->repaint();
或者ui->tableWidget->update()
钱豁,界面依然沒有自動(dòng)更新。
只有當(dāng)鼠標(biāo)點(diǎn)擊界面時(shí)屿脐,數(shù)據(jù)才被刷新涕蚤。
解決方法
使用如下代碼:
ui->tableWidget->viewport()->update();
原因
update()
是更新這個(gè)控件
viewport()->update()
是更新這個(gè)控件里面的內(nèi)容
進(jìn)一步分析
QTableWidget Class 官網(wǎng)的資料如下
http://doc.qt.io/qt-5/qtablewidget.html
順著繼承關(guān)系,一步步往上找的诵,會(huì)發(fā)現(xiàn)如下說明
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