×
Namespaces

Variants
Actions

Qt rounded rect widget

From Nokia Developer Wiki
Jump to: navigation, search
Article Metadata
Compatibility
Platform(s): S60 3rd Edition, FP1, FP2
S60 5th Edition
Symbian
Article
Keywords: QPainterPath ,QRegion
Created: srikanth_trulyit (29 May 2009)
Last edited: hamishwillee (11 Oct 2012)

This code snippet shows how to display QWidgets in rounded rectangle borders with transparency effect.

Overview

For this we need to reimplement QWidget::paintEvent() and do the following two simple steps:

  1. Clip the widget to a rounded rectangle
  2. Mask the widget with the clipped region

Preconditions

Code

 
void MyRoundedWidget::paintEvent(QPaintEvent *aPaintEvent)
{
 
qreal opacity(0.675);
int roundness(12);
QRect widget_rect = this->rect();
 
QPainter painter(this);
painter.save();
 
painter.setRenderHint(QPainter::Antialiasing);
painter.setPen(Qt::red);
 
// clip
QPainterPath rounded_rect;
rounded_rect.addRoundRect(1, 1, widget_rect.width() - 2, widget_rect.height() - 2, roundness, roundness);
painter.setClipPath(rounded_rect);
 
// get clipping region
QRegion maskregion = painter.clipRegion();
 
// mask the widget
setMask(maskregion);
painter.setOpacity(opacity);
 
// fill path with color
painter.fillPath(rounded_rect,QBrush(Qt::black));
 
// restore painter
painter.restore();
 
}


First create a painter path of a rounded rectangle

	QPainterPath rounded_rect;
rounded_rect.addRoundRect(1, 1, widget_rect.width() - 2, widget_rect.height() - 2, roundness, roundness);


Clip the widget to the created painter path which is a rounded rectangle. By clipping we are directing the painter to draw in the clipped region

painter.setClipPath(rounded_rect);

Now mask the widget to the clipped region after which it shows the rectangle with rounded edges only

	// get clipping region
QRegion maskregion = painter.clipRegion();
 
// mask the widget
setMask(maskregion);


If you dont want transparency effect set the opacity to 1.0

qreal opacity(1.0);
This page was last modified on 11 October 2012, at 04:18.
121 page views in the last 30 days.

Was this page helpful?

Your feedback about this content is important. Let us know what you think.

 

Thank you!

We appreciate your feedback.

×