Important: Please read the Qt Code of Conduct -

Semi-transparent QFrame

  • I need to make a QFrame semi-transparent when the mouse is not hovering on it. And make it opaque when the mouse moves on it.
    I have try QWidget::setWindowOpacity() which doesn't work. Obviously, the setWindowOpacity() works on a widget which has a Qt::Window flag.
    So, how can I make the QFrame semi-transparent.
    PS: I have set the css of the QFrame object, it has a png as its background.

  • Hi,

    it's not a full solution, but I think that it can be an idea for you.

    I've written a sample code, that is a widget, with a custom paint method.


    class Widget : public QWidget

    bool _over;
    bool _prevOver;

    void paintEvent(QPaintEvent *event);
    void mouseMoveEvent(QMouseEvent *event);

    Widget(QWidget *parent = 0);


    Widget::Widget(QWidget *parent)
    : QWidget(parent),

    void Widget::mouseMoveEvent(QMouseEvent *event)
    _over = QRect(rect().center()-QPoint(100,100),rect().center()+QPoint(100,100)).contains(event->pos());
    if (_over != _prevOver)
    _prevOver = _over;

    void Widget::paintEvent(QPaintEvent *event)
    QPainter p(this);

    p.drawText(rect(),"Hello world!",QTextOption(Qt::AlignCenter | Qt::AlignVCenter));
    p.fillRect(rect(),QColor(255,0,0,(_over)? 255 : 100));

    If you move the cursor out of a 100x100 pixel square from the center, you can see "Hello world!" covered with a semi-transparent color (so you can see it).
    If you move in the square, the color fully covers the text.

    So, you should modify the alpha of the png in a temporary QPixmap, and paint it, or something similar, if the transparent condition happens.


  • Thanks for the example. So I need to override the paintEvent.

Log in to reply