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();
}
答
为了执行这个任务,我们必须覆盖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());
}
}
在你的情况,你必须改变:
RubberBand.h
#include <QRubberBand>
[...]
QRubberBand rubberBand;
到
#include "customrubberband.h"
[...]
CustomRubberBand rubberBand;
完整代码:https://github.com/eyllanesc/stackoverflow/tree/master/qimvi
空隙橡皮:: 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
以上是我的代码 – mahesht
[编辑](https://stackoverflow.com/posts/44600861/edit)您的帖子并将其添加到那里 – eyllanesc