#ifndef RUBBERBANDSTYLE_H
#define RUBBERBANDSTYLE_H
#include <QBrush>
#include <QPainter>
#include <QPen>
#include <QProxyStyle>
#include <QRect>
#include <QStyleOptionRubberBand>
class RubberbandStyle : public QProxyStyle
{
typedef QProxyStyle base_type;
public:
RubberbandStyle(const QPen& pen, const QBrush& brush, QStyle* style = nullptr)
: QProxyStyle(style)
, pen_(pen)
, brush_(brush)
{
}
~RubberbandStyle() override
{
}
void drawControl(ControlElement element, const QStyleOption* option, QPainter* painter, const QWidget* widget = nullptr) const override
{
if (CE_RubberBand == element)
{
painter->save();
painter->setPen(pen_);
painter->setBrush(brush_);
painter->drawRect(option->rect.adjusted(0, 0, -1, -1));
painter->restore();
return;
}
base_type::drawControl(element, option, painter, widget);
}
private:
QPen pen_;
QBrush brush_;
};
使用方式
//橡皮筋的风格设置 ********************************
QPen pen(QBrush(Qt::red), 0, Qt::DotLine);
QBrush brush(Qt::transparent);
auto rubberbandStyle = new RubberbandStyle(pen, brush, nullptr);
rubberbandStyle->setParent(this);
viewport()->setStyle(rubberbandStyle);
//橡皮筋的风格设置 ********************************
源码分析:QGraphicsView的paintEvent中:
#if QT_CONFIG(rubberband)
// Rubberband
if (d->rubberBanding && !d->rubberBandRect.isEmpty()) {
painter.restore();
QStyleOptionRubberBand option;
option.initFrom(viewport());
option.rect = d->rubberBandRect;
option.shape = QRubberBand::Rectangle;
QStyleHintReturnMask mask;
if (viewport()->style()->styleHint(QStyle::SH_RubberBand_Mask, &option, viewport(), &mask)) {
// painter clipping for masked rubberbands
painter.setClipRegion(mask.region, Qt::IntersectClip);
}
viewport()->style()->drawControl(QStyle::CE_RubberBand, &option, &painter, viewport());
}
#endif
QWindowsXPStyle::drawControl中的源码:
#if QT_CONFIG(rubberband)
case CE_RubberBand:
if (qstyleoption_cast<const QStyleOptionRubberBand *>(option)) {
QColor highlight = option->palette.color(QPalette::Active, QPalette::Highlight);
p->save();
p->setPen(highlight.darker(120));
QColor dimHighlight(qMin(highlight.red()/2 + 110, 255),
qMin(highlight.green()/2 + 110, 255),
qMin(highlight.blue()/2 + 110, 255),
(widget && widget->isTopLevel())? 255 : 127);
p->setBrush(dimHighlight);
p->drawRect(option->rect.adjusted(0, 0, -1, -1));
p->restore();
return;
}
break;
#endif // QT_CONFIG(rubberband)