Qt Rubberband选择矩形透明

时间:2017-06-17 04:46:40

标签: c++ qt qt5

如何使橡皮筋选择透明?我尝试了这段代码,但它不起作用:

void RubberBand::mousePressEvent(QMouseEvent* event) { 
    if (event->buttons() != Qt::LeftButton) return; 
    if (rubberBand.isVisible()) {
        rubberBand.hide(); 
        return; 
     } 
     auto posItem = RelativeClippedCoordinates(event->globalPos()); 
     origin = CoordinatesItemToGlobal(pixmapItem, posItem); 
     selectionRect.setTopLeft(posItem); 
     rubberBand.setGeometry(QRect(origin, QSize())); 
     rubberBand.setStyleSheet("background-color:trasparent;"); 
     rubberBand.show(); 
}

1 个答案:

答案 0 :(得分:0)

要执行此任务,我们必须覆盖paintEvent方法并激活Qt::WA_TranslucentBackground属性。

<强> customrubberband.h

#ifndef CUSTOMRUBBERBAND_H
#define CUSTOMRUBBERBAND_H

#include <QRubberBand>

class CustomRubberBand : public QRubberBand
{
public:
    CustomRubberBand(Shape s, QWidget * p = 0);

protected:
    void paintEvent(QPaintEvent *);
};

#endif // CUSTOMRUBBERBAND_H

<强> customrubberband.cpp

#include "customrubberband.h"

#include <QPainter>

CustomRubberBand::CustomRubberBand(Shape s, QWidget *p): QRubberBand(s, p)
{
    setAttribute(Qt::WA_TranslucentBackground, true);
}

void CustomRubberBand::paintEvent(QPaintEvent *)
{

    if(isVisible()){
        QPainter painter(this);
        painter.setPen(Qt::blue);
        painter.setBrush(QBrush(QColor(85, 142, 253, 100)));
        painter.drawRect(rect());
    }
}

enter image description here

在您的情况下,您必须更改:

<强> RubberBand.h

#include <QRubberBand>
[...]
QRubberBand rubberBand;

#include "customrubberband.h"
[...]
CustomRubberBand rubberBand;

完整代码:https://github.com/eyllanesc/stackoverflow/tree/master/qimvi

相关问题