c++ - Qt Rubberband选择rect透明

标签 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(); 
}

最佳答案

为了执行此任务,我们必须覆盖 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/others/qimvi

关于c++ - Qt Rubberband选择rect透明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44600861/

相关文章:

c++ - 强制链接器因多定义错误而失败,即使包括 --whole-archive

c++ - 模板循环依赖问题

javascript - 如何使用 Qt WebEngine 和 QWebChannel?

c++ - 通过 Qt C++ 中的键访问解析的嵌套 JSON

c++ - QwtPlot setAxisScale,它是如何工作的?

c++ - 将函数指针作为模板参数传递

c++ - 如何在 visual studio 2017 中使用 zlib 库?

c++ - qt在qgridlayout中设置相同大小的小部件

qt - 使用 OpenGL 将图像渲染到子类 QDeclarativeItem

macos - 在 MacOSX 上,当指定无效的身份验证凭据时,QNetworkAccessManager 会进入无限循环