需求:主窗口每秒自動刷新顯示數據。標準方案:啟動 QTimer,連接 timeout() 信號到更新槽函數。
// 構造函數中
QTimer *timer = new QTimer(this);
connect(timer, &QTimer::timeout, this, &MainWindow::refreshData);
timer->start(1000); // 1000ms = 1s
// 槽函數
void MainWindow::refreshData() {
// 1. 從數據源獲取最新數據
// 2. 更新 UI 控件:label->setText(...), chart->updateSeries(...)
// 3. 若耗時操作,移至工作線程,通過信號傳回主線程更新 UI
}
timer->setSingleShot(false)(默認)循環觸發timer->setTimerType(Qt::PreciseTimer)QtConcurrent::run 或 QThreadshowEvent 啟動,hideEvent 停止定時器若數據源支持推送(WebSocket、MQTT、D-Bus),改用事件驅動比輪詢更高效。