Search code examples
c++qtqpainter

How to draw a transparent rectangle with colored corners in qt?


How to draw a transparent rectangle with colored corners in qt(using QPainter), like this one in the below image :

enter image description here


Solution

  • void Widget::paintEvent(QPaintEvent *) {
        draw(10,10,50,50);
    }
    
    void Widget::draw(int x,int y,int _width,int _height)
    {
        QPainter p(this);
        p.setPen(QPen(Qt::red,3,Qt::SolidLine));
        p.drawLine(x,y,x +0,_height/4+y);
        p.drawLine(x,y+ _height,x + 0,_height - _height/4+y);
        p.drawLine(x,y,x +_width/4,0+y);
        p.drawLine(x,y+_height,x +_width/4,_height+y);
        p.drawLine(_width+x,y+_height,x +_width - _width/4,_height+y);
        p.drawLine(_width+x,y+_height,x +_width,_height - _height/4+y);
        p.drawLine(_width+x,y,x + _width-_width/4,0+y);
        p.drawLine(_width+x,y,_width+x,_height/4+y);
        //custom brush for rectangle
        //p.fillRect(x,y,_width,_height,QBrush(QColor(40,0,0,50)));
    }