12

Is it possible to display translucent and/or irregular-shaped windows with Qt?

(I'm assuming it ultimately depends on the capabilities of the underlying GUI system, but let's assume at least Windows XP / Mac OS X)

If so, how does one accomplish this?

Tony the Pony
  • 40,327
  • 71
  • 187
  • 281

2 Answers2

11

Yes, it is possible. The key is the Qt::WA_TranslucentBackground attribute of QWidget

Here is a simple class that draws a round translucent window with a red background 50% alpha.

TranslucentRoundWindow.h:

#include <QWidget>

class TranslucentRoundWindow : public QWidget
{
    public:
        TranslucentRoundWindow(QWidget *parent = 0);
        virtual QSize sizeHint() const;

    protected:
        virtual void paintEvent(QPaintEvent *paintEvent);
};

TranslucentRoundWindow.cpp:

#include <QtGui>

#include "TranslucentRoundWindow.h"

TranslucentRoundWindow::TranslucentRoundWindow(QWidget *parent) : QWidget(parent, Qt::FramelessWindowHint)
{
    setAttribute(Qt::WA_TranslucentBackground);
}

QSize TranslucentRoundWindow::sizeHint() const
{
    return QSize(300, 300);
}

void TranslucentRoundWindow::paintEvent(QPaintEvent *)
{
    QPainter painter(this);
    painter.setRenderHint(QPainter::Antialiasing);
    painter.setPen(Qt::NoPen);
    painter.setBrush(QColor(255, 0, 0, 127));

    painter.drawEllipse(0, 0, width(), height());
}

If you want to be able to move this window with the mouse, you will have to override mousePressEvent, mouseMoveEvent and mouseReleaseEvent.

0xced
  • 25,219
  • 10
  • 103
  • 255
  • Copied & pasted above and all I get is a black square with a red circle inside. What am I missing? – slashmais Jan 17 '12 at 16:10
  • On what OS have you tried? This works fine on Windows and OS X. Also, what Qt version are you using? This answer was written with Qt 4.4 or 4.5 if I remember correctly. – 0xced Jan 17 '12 at 19:31
  • Linux 3.1.0 64bit, Qt 4.6.3. The examples that comes with QT all work fine. – slashmais Jan 17 '12 at 19:45
  • On Windows you have to had `setWindowFlags(Qt::FramelessWindowHint);` in the window constructor. – Cyril Leroux May 12 '13 at 12:20
3

It certainly is possible. Qt ships with the "Shaped Clock" demonstration. The documentation of which is here.

It creates a top-level window with an odd shape. Should be all you need.

Thomi
  • 11,647
  • 13
  • 72
  • 110