最近有點時間,就研究研究Qt ,提升一下自己
我記得我在剛開始學習Qt 的時候,想要在一個控件上面繪制圖形,那就要建構一個新類來調用該控件的繪圖函數
今天看到了狗哥的學習部落格,感覺自己好渺小啊,按照狗哥的步驟,一步一步來練習,寫了一個demo
Qt 之是以不能在在任意控件上面繪圖,是因為Qt的事件過濾器把控件的繪圖事件給過濾了,自己知識不夠,盜用狗哥的話
“在事件過濾器
eventFilter()
中攔截 Label 的
QEvent::Paint
事件”
代買如下
bool Widget::eventFilter(QObject *watched, QEvent *event)
{
if(watched == ui->label && event->type() == QEvent::Paint)
{
magicTime();
}
return QWidget::eventFilter(watched,event);
}
然後就是在magicTime()函數中實作自己的繪制了
如下demo
void Widget::magicTime()
{
QPainter painter(ui->label);
painter.setPen(Qt::gray);
painter.setBrush(Qt::green);
painter.drawRect(10,10,200,200);
}
不過在此之間,還有一個步驟是要做的
ui->label->installEventFilter(this);
這句話是必不可少啊,
源代碼位址:
Qt5.6.0mingW:http://download.csdn.net/detail/z609932088/9468793
運作截圖