How to draw a colored Rectangle with a dashed outline in Qt

How to draw a colored Rectangle with a dashed outline in Qt

Implementing the drawing and painting in Qt

Table of contents

Introduction

Hi All,

Wishing you and your family a very Happy New Year!

When I accidentally stumbled upon hashnode, I got an opportunity that I had been waiting for too long. I have always wanted to document my journey of Qt in a platform so that other newbies can be benefitted from it. I am so glad that I found this wonderful platform to share my journey with.

I keep experimenting with Qtcreator and try to break down a bigger problem into smaller chunks so that I can try them out separately in an independent project file. Drawing and painting are one of the important concepts of UI in Qt. So, presenting the result of one of those random experiments below:

Steps

To draw a colored rectangle with dashed outline

Step 1: Define a rectangle with its dimension and position on the screen

Step 2: Create and Customize pen for drawing the outline For customizing; use setStyle and setColor() If the color to be used of QtGlobal then can directly use, otherwise use setRgb() for the QColor object.

Step 3: Create and Customize brush for drawing the outline

Step 4: Set the brush and pen by using the object of the Qpainter

Step 5: Start to draw the rectangle by using the object of QPainter and drawRect(rectangle_obj)

Codes


//Dimensions and position of rectangle in the screen are defined ;
    QRectF rectangle(10.0, 20.0, 80.0, 60.0);

   //Creating and customizing the pen and brush ; pen for the outline and brush for filling

    // Cutomised Pen; color:black , style:dashed
    QPen dashpen;
    dashpen.setStyle(Qt::DashLine);
    dashpen.setColor(Qt::black);

    // Customizing Brush ; pattern: Solid Pattern , Color:Orange ; other than Global Color
    QBrush bdashrec;
    QColor orange;
    orange.setRgb(255,140,0);
    bdashrec.setStyle(Qt::SolidPattern);
    bdashrec.setColor(orange);

    //For drawing rectangle : a) outline with customised pen;dashpen [QPen object with style:dashpen and color:black]
    // b)filling it with orange color
    painter.setPen(dashpen);
    painter.setBrush(bdashrec);
    // painter.setBrush(QColorConstants::svg::'#ff8c00'); for QColorConstants header file

    painter.drawRect(rectangle);

Draw&PaintRectangle.PNG

Did you find this article valuable?

Support Swati Sarangi by becoming a sponsor. Any amount is appreciated!