We all know that the QT designers directly drag the button is rectangular with rounded corners of the pattern, then how do we set the custom button?
To design a button, we have to know what property the button has, first, the button must have a position
Second, the button must have a name. And how he reacts when we click the button. So we define two classes,
a qrect _rect; (or qpoint more appropriate)
The second one is QString _text;
Since there is a reaction, then we first think of is the mouse event, add a bool _press;
as well void Mousepressevent (Qmouseevent *), and mousereleaseevent (Qmouseevent *);
First we need to initialize the location inside the constructor.
Mybutton::mybutton (const QString text,qwidget *parent)
constructor, parent class is Widget
Qrect (0,0,90,25); Position is 0, 0 length is 90, width is 25
_text (text); or _text = text;
In general, we are in the painevent inside the thing, Draw button is also so, according to your favorite style, such as bloggers like the oval.
void MyButton::p ainevent (qpainevent *)
{
Qpainter p (this);
P.drawellipse (_rect); There are 4 parameters, namely position and length width, if the length and width are equal to a standard circle.
P.drawtext (_rect,_text,qtextoption (Qt::aligncenter);
Set the text to have three parameters, namely object, text, text position
}
If we need to click the left mouse button to change color, we can use ture or false to handle
void Mybutton::mousepressevent (Qmouseevent *)
{
_press = true;
This->update (); Click to update, call Painevent
}
void Mybutton::mousereleaseevent (Qmouseevent *)
{
_press = false;
This->update (); Click to update, call Painevent
}
void MyButton::p ainevent (qpainevent *)
{
if (_press ==false)
P.setbrush (Qt::d Arkyello); Paint your favorite colors with a brush
Else
P.setbrush (Qt::d arkgreen);
}
This article belongs to Bo Master original, if need to reprint, please indicate the source
Author: Ten10
QT 5 Mini Practice Pure code Making custom buttons