Not able to get transparent QRubberband

时间:2017-06-06 16:28:47

标签: qt

I am trying to draw a rectangle using QRubberBand. I need the rectangle border to be opaque and its inside to be transparent. But, I am able to do it only other way around, with the border to be transparent and its filling in opaque. Here is the code I am using,

class roiFrame : public QRubberBand
{
public:
    roiFrame(Shape s, QWidget * p = 0):QRubberBand(s, p){}
    ~roiFrame(){}


protected:
    void paintEvent(QPaintEvent *pe)
    {
        Q_UNUSED(pe);

        QStyleOptionRubberBand opt;
        QStylePainter painter(this);
        painter.setOpacity(0.8); // from aamer4yu
        opt.initFrom(this);
        //  opt.opcatiy = false; //This one also makes the border to be transparent .
        painter.drawControl(QStyle::CE_FocusFrame, opt);
    }
};

As an alternative, I tried to draw a rectangle using QPainter::drawRect:

myWindow::myWindow(QWidget *parent): QFrame(parent)
{
    ui.setupUi(this);
}

myWindow::~myWindow()
{
}

void myWindow::mouseReleaseEvent(QMouseEvent * event)
{
    releaseX = event->x();
    releaseY = event->y();
}

void myWindow::mousePressEvent(QMouseEvent * event)
{
    pressX = event->x();
    pressY = event->y();
}

void myWindow::paintEvent(QPaintEvent *event)
{
    QFrame::paintEvent(event);
    QRectF rectangle(pressX,pressY,releaseX,releaseY);
    QPainter painter(this);
    painter.setOpacity(0.8);
    painter.drawRect(rectangle);
    painter.end();
}

1 个答案:

答案 0 :(得分:0)

drawRect的问题在于您没有指定矩形的外观,即边框及其内部的属性:

在您的情况下,只应绘制边框。所以,你应该使用这样的东西:

painter.setPen(Qt::red);

<强>说明

  • 请注意,可能需要调用QWidget::update来强制重绘事件。
  • 请注意QRectF的第三个和第四个构造函数参数是宽度和高度,而不是右下角坐标。作为替代方案,您可以使用following constructor overloadQRectF rectangle(QPointF(pressX,pressY),QPointF(releaseX,releaseY));