paintEvent(QPaintEvent *)函數重載

paintEvent(QPaintEvent *)函數是QWidget類中的虛函數,用於ui的繪製,會在多種情況下被其他函數自動調用,比如update()時。下面簡單說一下繪製界面時所需要的東西。

1.QPainter

這個類主要提供在窗體或者其他繪圖設備上進行繪圖的功能,在paintEvent(QPaintEvent *)中使用如下:

QPainter painter(this);

此類中常用的函數有:

drawXXX()函數,用於繪製圖形、文字和路徑等;

fillXXX()函數,用於填充,可在指定區域內進行填充;

brush()和pen()  筆刷和鋼筆的相關操作

2.QPainterPath

這個類爲繪圖提供容器,主要還是用於描述繪製路徑。可以通過函數setFillRule(Qt::WindingFill);來設置填充規則,通過addRect()函數來添加繪製區域。

 

3.QColor

此類提供顏色支持,這裏的顏色可以定義四個屬性:QColor ( int r, int g, int b, int a = 255 ),即紅、綠、藍和透明度。除此之外,也可以單個設置這四個值,通過類似setAlpha()的函數即可設置,這對設計漸進效果很有幫助。

 

下面送上一段摘自別人項目中的代碼,僅供參考學習。

void ABC::paintEvent(QPaintEvent *)
{
    QPainterPath path;
    path.setFillRule(Qt::WindingFill);
    path.addRect(10, 10, this->width()-20, this->height()-20);

    QPainter painter(this);
    painter.setRenderHint(QPainter::Antialiasing, true);
    painter.fillPath(path, QBrush(Qt::white));

    QColor color(0, 0, 0, 50);
    for(int i=0; i<10; i++)
    {
        QPainterPath path;
        path.setFillRule(Qt::WindingFill);
        path.addRect(10-i, 10-i, this->width()-(10-i)*2, this->height()-(10-i)*2);
        color.setAlpha(150 - qSqrt(i)*50);
        painter.setPen(color);
        painter.drawPath(path);
    }
}


 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章