QRubberBand类提供了一个矩形或直线,可以指示选择或边界。常见的模式是结合鼠标事件来执行此操作。本文将使用框选QCheckBox控件,来演示QRubberBand是如何配合鼠标进行工作的。
#ifndef RUBBERBAND_H
#define RUBBERBAND_H
#include <QRubberBand>
class QPaintEvent;
class RubberBand : public QRubberBand
{
Q_OBJECT
public:
explicit RubberBand(Shape s, QWidget * p = 0);
protected:
void paintEvent(QPaintEvent *event);
};
#endif // RUBBERBAND_H
#include "rubberband.h"
#include <QPainter>
#include <QPaintEvent>
RubberBand::RubberBand(QRubberBand::Shape s, QWidget *p) :
QRubberBand(s, p)
{
}
void RubberBand::paintEvent(QPaintEvent *event)
{
QRubberBand::paintEvent(event);
//
QPainter p(this);
QFont ft = font();
ft.setFamily("microsoft yahei");
ft.setPixelSize(14);
p.setFont(ft);
p.setPen(QPen(Qt::white, 2));
int w = size().width();
int h = size().height();
if(w >10 && h >10)
{
QString text = QString("%1,%2").arg(w).arg(h);
p.drawText(rect(), Qt::AlignTop|Qt::AlignHCenter, text);
}
}
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QMouseEvent>
#include "rubberband.h"
MainWindow::MainWindow(QWidget *parent)
: QWidget(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::mouseMoveEvent(QMouseEvent *event)
{
m_lastpos = event->globalPos();
QRect rc(m_startpos, m_lastpos);
m_rubberBand->setGeometry(rc.normalized());
m_rubberBand->show();
}
void MainWindow::mousePressEvent(QMouseEvent *event)
{
if (event->button() == Qt::LeftButton)
{
if (nullptr == m_rubberBand)
m_rubberBand = new RubberBand(QRubberBand::Rectangle);
m_startpos = event->globalPos();
m_rubberBand->setGeometry(QRect(m_startpos, QSize()));
//m_rubberBand->show();
}
}
void MainWindow::mouseReleaseEvent(QMouseEvent *event)
{
QRect rect = m_rubberBand->geometry();
QList<QCheckBox*> checks = findChildren<QCheckBox*>();
for (auto v : checks)
{
QPoint point = v->mapToGlobal(QPoint(0, 0));
if(rect.contains(point) /*&& v->inherits("QCheckBox")*/){
v->setChecked(true);
}
}
//
if(m_rubberBand){
delete m_rubberBand;
m_rubberBand = nullptr;
}
}