在做GUI開發時,要讓控制元件重繪,會呼叫update函式;那么在呼叫了update函式后,Qt究竟基于什么原理、執行了什么代碼使得螢屏上有變化?本文就帶大家來探究探究其內部原始碼,
Qt手冊中關于QWidget::update()解釋如下::
Updates the widget unless updates are disabled or the widget is hidden.
This function does not cause an immediate repaint; instead it schedules a paint event for processing when Qt returns to the main event loop. This permits Qt to optimize for more speed and less flicker than a call to repaint() does.
Calling update() several times normally results in just one paintEvent() call.
Qt normally erases the widget's area before the paintEvent() call. If the Qt::WA_OpaquePaintEvent widget attribute is set, the widget is responsible for painting all its pixels with an opaque color
對于如上英文,解釋如下::
重繪控制元件,除非重繪被禁用或者控制元件是隱藏的,
此函式不會導致立即重繪; 相反,它調度一個paint事件,在Qt回傳主事件回圈時處理,這允許Qt進行優化,以獲得比呼叫repaint()更快的速度和更少的閃爍,
多次呼叫update()通常只會導致一次paintEvent()呼叫,
Qt通常在呼叫paintEvent()之前擦除控制元件區域,如果設定了Qt::WA_OpaquePaintEvent屬性,控制元件用不透明的顏色繪制其所有像素,
void QWidget::update()原始碼如下
void QWidget::update()
{
update(rect());
}
即呼叫update沒有傳遞引數,則默認重繪控制元件的整個區域,呼叫如下多載的update函式

1、如果控制元件是隱藏或者重繪被禁用,則直接回傳
2、引數傳遞的矩形與控制元件矩形的交集,如果為空,則直接回傳
3、如果支持BackingStore(默認支持),則標臟該控制元件所屬的頂層視窗(TLW:: topLevelWidget縮寫)區域,即呼叫tlwExtra->backingStoreTracker->markDirty(r, this);函式

其中入參updateTime的值為UpdateLater,而非UpdateNow;
函式主體內容如下::
1、把控制元件加入到dirtyWidgets容器中(addDirtyWidget函式)
2、通知tlw進行重繪(sendUpdateRequest函式)
sendUpdateRequest函式如下圖所示,其Post一個QEvent::UpdateRequest事件,即放入事件佇列中,立即回傳;QEvent::UpdateRequest事件的接受者為tlw;

看到這里,也就明白為什么update是異步重繪了,原始碼面前了無秘密
Qt update重繪之原始碼分析系列會分拆為多個具體的文章,后續我會一一講解并發布
由于這里不能發布視頻,所以我在這發布了文章,在我的微信公眾號里同步發布了詳細的PPT以及視頻進行詳細解說
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/257307.html
標籤:C++
