Qt 在控件上面绘图 label,pushbutton。。。。。
1、构建一个新类来调用该控件的绘图函数,新类重写 paintEvent(QPaintEvent *)
▶构建:
class DrawGraphLab : public QLabel
{
Q_OBJECT
public:
explicit DrawGraphLab( QWidget* parent = 0);
protected:
void paintEvent(QPaintEvent *event);
};
▶实现:
DrawGraphLab::DrawGraphLab(QWidget* parent) : QLabel(parent)
{
}
void DrawGraphLab::paintEvent(QPaintEvent *)
{
//绘制线条
QPainter painter;
painter.begin(this);
painter.setPen(QPen(QColor(132, 130, 130) ,4) );
painter.drawLine(951/2, 120, 951/2, 430);
painter.drawRect(10,10,200,200);
painter.end();
}
▶▶调用
void RoutePage::init_ui()
{
QLabel* p_station_tab = new QLabel(this);
p_station_tab->setGeometry(79, 66, 951, 537 );
p_station_tab->setPixmap(QPixmap(":/res/Route/icon_station_show.png"));
//在p_station_tab控件上绘制图形
DrawGraphLab* p_draw_graph_lab = new DrawGraphLab(p_station_tab);
p_draw_graph_lab->setGeometry( p_station_tab->geometry() );
}
2、Qt的事件过滤器去不需要过滤的绘图控件。即重写eventFilter(QObject *watched, QEvent *event) (不需要构建新类)
//Qt 之所以不能在在任意控件上面绘图,是因为Qt的事件过滤器把控件的绘图事件给过滤了
▶添加类成员
class RoutePage : public QDialog
{
Q_OBJECT
public:
explicit RoutePage(QWidget *parent = 0);
~RoutePage();
void init_ui();
QLabel* p_station_tab;
QLabel* p_draw_graph_lab;
bool eventFilter(QObject *watched, QEvent *event);
void magicTime();
}
▶重写eventFilter
bool RoutePage::eventFilter(QObject *watched, QEvent *event)
{
if(watched == p_draw_graph_lab && event->type() == QEvent::Paint)
{
magicTime();
}
return QWidget::eventFilter(watched,event);
}
void RoutePage::magicTime()
{
qDebug()<<"fdskjfhjksdhfjksdhfkjsdhfksdjhfdsjfkjsdh";
QPainter painter;
painter.begin(p_draw_graph_lab);
painter.setPen(QPen(QColor(132, 130, 130) ,4) );
painter.drawLine(951/2, 120, 951/2, 430);
painter.drawRect(10,10,200,200);
painter.end();
}
▶▶调用
void RoutePage::init_ui()
{
p_station_tab = new QLabel(this);
p_station_tab->setGeometry(79, 66, 951, 537 );
p_station_tab->setPixmap(QPixmap(":/res/Route/icon_station_show.png"));
//在p_station_tab控件上绘制图形
p_draw_graph_lab = new DrawGraphLab(p_station_tab);
p_draw_graph_lab->setGeometry( p_station_tab->geometry() );
//在主Widget加入过滤事件
p_draw_graph_lab->installEventFilter(this);
}