Qt Snippet: Rounded corners QPushButton inside QGraphicsScene

QGraphicsScene is a great Qt component allowing to develop full graphics applications (like game for example) in a very easy way. As additional feature is possible to insert a QWidget based object inside the scene through the QGraphicsProxyWidget item.



This is very useful in case you need to add some control, like a button, inside your graphic application. Without this feature the only alternative would be to develop a graphic item able to work as a button. Add a button is very simple and using the QPushButton component (or QToolButton) have the advantage you can use Qt stylesheet for make the button a little more beautiful to see. In this particular example we want to make the button red with rounded corners as follow:

QPushButton *pButtonWidget = new QPushButton();
pButtonWidget->setGeometry(QRect(0, 0, 150, 100));
pButtonWidget->setText("Test");
pButtonWidget->setFlat(true);
pButtonWidget->setStyleSheet(
    "background-color: darkRed;"
    "border: 1px solid black;"
    "border-radius: 15px;"
    "color: lightGray; "
    "font-size: 25px;"
    );
QGraphicsProxyWidget *pButtonProxyWidget = scene()->addWidget(pButtonWidget);

As you can see the code is very short and simple, however running the application we'll can see a result like this:


The button have rounded corners but it's still painted as a rectangle and the angles outside the rounded corners was filled using the same color of the button itself that is not the result we want o obtain. Fortunately for fix this issue we only need to set the button attribute WA_TranslucentBackground as you can see in the additional red line:

QPushButton *pButtonWidget = new QPushButton();
pButtonWidget->setGeometry(QRect(0, 0, 150, 100));
pButtonWidget->setText("Test");
pButtonWidget->setFlat(true);
pButtonWidget->setAttribute(Qt::WA_TranslucentBackground);
pButtonWidget->setStyleSheet(
    "background-color: darkRed;"
    "border: 1px solid black;"
    "border-radius: 15px;"
    "color: lightGray; "
    "font-size: 25px;"
    );
QGraphicsProxyWidget *pButtonProxyWidget = scene()->addWidget(pButtonWidget);

Making this change will have the result to create a button showing as expected. You can see the result below:


Comments

  1. Thanks a lot, this was just what I have been looking for! Finally got my pushbutton nice and round without any background clutter.

    ReplyDelete

Post a Comment

Popular posts from this blog

Access GPIO from Linux user space

Android: adb push and read-only file system error

Tree in SQL database: The Nested Set Model