Tuesday, March 29, 2011

Qt Style Sheet (Qt Skin)

Fancy seeing application with unusual shape and its ability to customize the color, background etc...

You can do it easily with Qt...

Qt supports Style-Sheet like CSS in HTML. Here is the example:

.QLabel
{
color: white;
}


#MyForm #lblCaption
{
font: normal 10pt "Tahoma";
color: white;
}


In above example, all QLabel object will have white foreground and the object called lblCaption inside class MyForm will have font as stated with white foreground.

To have a dialog with round-border corner, add the following to the style sheet:

QDialog
{
border-radius: 9px;
}


But of course you need to mask the window to make it round on the corner.

There are two way to achieve this.

First, prepare a bitmap with as the same size as your window and perform a mask over the window. The transparent part of the bitmap will be mask off, creating non rectangular window.

The second way is to generate the pixmap programmatically and then use it to mask the window. But of course if you would like to have very funny shape, it might be difficult to do it programmatically.

Below are the code to create the rounded corner window programatically.

int roundness(double size)
{
const int Diameter = 15;
return 100 * Diameter / int(size);
}


QPixmap GetDialogMask(int width, int height)
{
QPixmap pixmap(width, height);
pixmap.fill(Qt::transparent);

QPainter painter( &pixmap );

QPainterPath painterPath;
painterPath.addRoundRect(0, 0, pixmap.width() - 1, pixmap.height() - 1, roundness(pixmap.width()), roundness(pixmap.height()));
painter.setClipPath(painterPath);

painter.fillPath(painterPath, QBrush(Qt::white));

return pixmap;
}


To apply the mask to the dialog, add this to the constructor of your dialog:
QPixmap pixmap = GetMaskPixmap(this->width(), this->height());
this->setMask (pixmap.mask());

If you save your style to a file, what you can do is to load the style and store it to the string (i.e. gStyleSheet) and apply the style sheet using the code below.
qApp->setStyleSheet(gStyleSheet);

Yup that is all what you need to do....

To learn more about Qt Style Sheet, click here