Qt橡皮筋选择矩形透明

问题描述:

如何使橡皮筋选择透明?我想这个代码,但它不工作:Qt橡皮筋选择矩形透明

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(); 
} 
+0

空隙橡皮:: mousePressEvent(QMouseEvent *事件) { \t如果(事件 - >按钮() != Qt :: LeftButton)return; \t if(rubberBand.isVisible()) \t { \t \t rubberBand.hide(); \t \t return; \t} \t auto posItem = RelativeClippedCoordinates(event-> globalPos()); \t origin = CoordinatesItemToGlobal(pixmapItem,posItem); \t selectionRect.setTopLeft(posItem); rubberBand.setGeometry(QRect(origin,QSize())); rubberBand.setStyleSheet(“background-color:trasparent;”); rubberBand.show(); } – mahesht

+0

以上是我的代码 – mahesht

+0

[编辑](https://stackoverflow.com/posts/44600861/edit)您的帖子并将其添加到那里 – eyllanesc

为了执行这个任务,我们必须覆盖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

+0

我试过了,但没有奏效。背景颜色仍然是蓝色。 – mahesht

+0

您可以显示您拥有的屏幕截图吗? – eyllanesc

+0

我已添加图片。点击“橡皮筋做透明” – mahesht