How to leave a transparent window using Qt?

3

I'm developing a college job at Qt . I would like to make the background of my application transparent. I researched a little and the function I found was:

this->setWindowOpacity(0);

However, Qt applies opacity to the entire window. I would like the components I added, like buttons or even drawings using QPainter , to maintain their normal opacities, ie I would not like to apply opacity to the window components, just in the frame.

I'm using Debian 7.1 with Gnome 3.4.2.

At the moment I'm having this result:

Noticethattransparencyappliedtothebuttontoo.

Iremovedsomethingsfrommyapplicationinordertomakeiteasierformetosolvemyproblem.Hereisthecode:

Window.h

#ifndefJANELA_H#defineJANELA_H#include<QMainWindow>#include<QFrame>#include<QPushButton>#include<QWidget>#include<QVBoxLayout>#include<QPainter>#include<QPen>classJanela:publicQMainWindow{Q_OBJECTpublic:Janela();~Janela();voidpaintEvent(QPaintEvent*event);public:QFrame*frame;QPushButton*botao;intpos_x=280,pos_y=280;};#endif//JANELA_H

Window.cpp

#include<Janela.h>Janela::Janela(){QFrame*frame=newQFrame();QVBoxLayout*layout=newQVBoxLayout();this->setWindowOpacity(0.80);setCentralWidget(frame);setWindowTitle(QString::fromUtf8("Exemplo de QFrame"));

    frame->setLineWidth(4);
    frame->setFrameStyle(QFrame::Box);
    frame->setFixedSize(300,300);
    frame->resize(300, 300);
    frame->setMinimumSize(300,300);
    frame->setMaximumSize(300,300);
    frame->setLayout(layout);

    botao = new QPushButton("Pressione-me");
    layout->addWidget(botao);

    show();
    frame->setFocus();

};

Janela::~Janela(){};

void Janela::paintEvent(QPaintEvent *event){
    QPainter painter(this);
    painter.setPen(Qt::green);
    painter.setBrush(Qt::green);
    painter.drawEllipse(10,10,10,10);
    painter.fillRect(pos_x,pos_y,10,10,Qt::red);
}

main.cpp

#include "Janela.h"
#include <QApplication>

int main(int argc, char **argv){
    QApplication app(argc, argv);

    Janela *janela = new Janela();

    return app.exec();
}
    
asked by anonymous 15.05.2014 / 08:08

1 answer

4

You can do this by activating the Qt::FramelessWindowHint flag in Janela master.

Janela::Janela() : QMainWindow(NULL, Qt::FramelessWindowHint)

And then turn on the Qt::WA_TranslucentBackground attribute to make the background invisible:

setAttribute(Qt::WA_TranslucentBackground);

The result is this:

Tomakethebackgroundtranslucent,notjustinvisible,youaddinPaintEventthebackgroundpatternyouwant.Example:

QPainterpainter(this);//Parausaracorpadrãodebackgrounddosistema.QColorbackground_color=palette().color(QPalette::Background);background_color.setAlpha(128);painter.setBrush(QBrush(background_color));//Defineumaborda.painter.setPen(QColor("#888"));

// Desenha o novo background da janela, antes de qualquer outra coisa.
painter.drawRect(0, 0, width()-1, height()-1);

And the result is this:

    
15.05.2014 / 16:09