Qt QRubberBand 如何实现鼠标框选控件

QRubberBand类提供了一个矩形或直线,可以指示选择或边界。常见的模式是结合鼠标事件来执行此操作。本文将使用框选QCheckBox控件,来演示QRubberBand是如何配合鼠标进行工作的。

一、RubberBand 框选效果图

Qt QRubberBand 如何实现鼠标框选控件_第1张图片

二、RubberBand 代码

  • rubberband.h
#ifndef RUBBERBAND_H
#define RUBBERBAND_H
#include 

class QPaintEvent;
class RubberBand : public QRubberBand
{
    Q_OBJECT
public:
    explicit RubberBand(Shape s, QWidget * p = 0);
protected:
    void paintEvent(QPaintEvent *event);
};

#endif // RUBBERBAND_H
  • rubberband.cpp
#include "rubberband.h"
#include 
#include 

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 
#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;
    }
}

你可能感兴趣的:(Qt,从入门到精通,qt,开发语言,QRubberBand,QCheckBox)