QT 绘制按钮 paintEvent enterEvent leaseEvent mouseEvent

时间:2021-09-29 04:19:36

案例2:绘制按钮

main.cpp

#include<QApplication>

#include “demoWidget.h”

int  main(int  args , int argv)

{

QApplication  app(args , argv);

DemoWidget w;

w.resize(400,400);

w.setVisible(true);

return  app.exec();

}

main.pro

TEMPLATE=app

SOURCES=main.cpp demoWidget.cppdemoPushButton.cpp

HEADERS=demoWidget.h demoPushButton.h

CONFIG=release qt

QT=core gui

TARGET=main

demoWidget.h

#ifndef DEMO2_WIDGET_H

#define DEMO2_WIDGET_H

#include<QWidget>

#include “demoPushButton.h”

class  DemoWidget: public QWidget

{

public:

DemoWidget(QWidget * parent=NULL);

public:

DemoPushButton * btn;

};

#endif

demoWidget.cpp

#include “demoWidget.h”

#include “demoPushButton.h”

DemoWidget::DemoWidget(QWidget *parent):QWidget(parent)

{

btn = new DemoPushButton(this);

btn->resize(100,30);

btn->move(100,100);

}

绘制按钮:

demoPushButton.h

#include<QPushButton>

#include<QPaintEvent>

#include<QMouseEvent>

#ifndef DEMO2_PUSHBUTTON_H

#define DEMO2_PUSHBUTTON_H

class DemoPushButton : public QPushButton

{

public:

DemoPushButton(QWidget * parent=NULL);

protected:

virtual void paintEvent(QPaintEvent * e);

virtual void  enterEvent(QEvent * e);

virtual void  leaveEvent(QEvent * e);

virtual void  mouseEvent(QMouseEvent*e);

private:

bool  israised;

};

#endif

demoPushButton.cpp

#include “demoPushButton”

#include<QColor>

#include<QBrush>

#include<QPen>

#include<QPoint>

#include<QPainter>

DemoPushButton::DemoPushButton(QWidget*parent)

:QPushButton(parent),israised(true)

{

setMouseTracking(true);   //跟踪鼠标移动事件

}

void DemoPushButton::paintEvent(QPaintEvent* e)

{

//绘制按钮的边界

int  w=width();   //按钮宽度

int  h=height();   //按钮高度

QColor clrw(255,255,255);

QColor clrb(0,0,0);

QBrush brw(clrw);

QBrush brb(clrb);

QPen  penw(brw,2);

QPen  penb(brb,2);

QPoint  pttop(w/2,0);

QPoint ptbottom(w/2,h);

QPoint ptleft(0,h/2);

QPoint ptright(w,h/2);

QPainter  g(this);

if(israised)

{

g.setPen(penw);

}

else

{

g.setPen(penb);

}

g.drawLine(pttop,ptleft);

g.drawLine(pttop,ptright);

if(israised)

{

g.setPen(penb);

}

else

{

g.setPen(penw);

}

g.drawLine(ptbottom,ptleft);

g.drawLine(ptbotton,ptrright);

}

void DemoPushButton::enterEvent(QEvent * e)

{

israised=false;

repaint();     //重新绘制按钮

}

void DemoPushButton::leaveEvent(QEvent * e)

{

israised=true;

repaint();

}

void DemoPushButton::mouseEvent(QMouseEvent * e)

{

float  w=this->width();

float  h=this->height()

int  x=e->x();

int  y=e->y();

float k=h/w;    //斜率

if( y>-k*x+h/2 &&

y>=k*x-h/2 &&

y<=k*x+h/2 &&

y<=-k*x+3*h/2)

{

israise=false;

}

else

{

israise=true;

}

repaint();

}