Rubber bands are often used in graphic editing applications, such as selecting a certain area of the image. The most common thing is to drag the mouse on the system desktop to draw a selection area similar to the ant line, and the selection line can be scaled with the movement of the mouse, so it is called the rubber band line.
In QT, the class used to describe the rubber band is qrubberband. Of course, a single qrubberband class still cannot produce the effect of the rubber band. In addition, there must be a combination of mouse events, you can click, drag, and release the mouse events that work with qrubberband. You can define a rubber band class Rubber as follows:
Class rubber: Public qwidget
{
Q_object
Public:
Rubber (qwidget * parent );
~ Rubber ();
Void mousepressevent (qmouseevent *);
Void mousemoveevent (qmouseevent *);
Void mousereleaseevent (qmouseevent *);
PRIVATE:
Qrubberband * rubberband;
Qpoint origin;
};
In the header file, specify the constructor and destructor, and the corresponding mouse RESPONSE event. Set qrubberband as a private object, and the origin is used to save the coordinates when the mouse clicks.
#include "rubber.h"
Rubber::Rubber(QWidget *parent)
{
setParent(parent);
this->setBackgroundRole(QPalette::Light);
this->setAutoFillBackground(true);
resize(400,360);
setWindowTitle("Rubber");
rubberBand = NULL;
}
The constructor completes the settings of the form size and background.
void Rubber::mousePressEvent(QMouseEvent *e)
{
origin = e->pos();
if(!rubberBand)
rubberBand = new QRubberBand(QRubberBand::Rectangle,this);
rubberBand->setGeometry(QRect(origin,QSize()));
rubberBand->show();
}
When you press the mouse in the form, create a qrubberband class. qrubberband: rectangle is the type of the rubber band. The effect of this line is to depict a Square area, another type is qrubberband: line, which is a square area filled with straight lines, equivalent to a shaded Square area. The most widely used function of qrubberband is setgeometry (). It sets the position and size of the rubber band.
When the mouse is pressed and the mouse moves, the area of the rubber line is displayed. Drag the event function to reload the event function and change the area size from qrect (origin, e-> pos ()). the normalized () function returns a qrect object, but the length and width of the object are all greater than zero.
void Rubber::mouseMoveEvent(QMouseEvent *e)
{
if(rubberBand)
rubberBand->setGeometry(QRect(origin,e->pos()).normalized());
}
When the mouse is released, the rubber band line can be hidden.
void Rubber::mouseReleaseEvent(QMouseEvent *e)
{
if(rubberBand)
rubberBand->hide();
}