简体   繁体   中英

how to switch non-transparent to transparent background child window

#include "trasparentwin.h"
#include <QHBoxLayout>
#include <QWidget>
#include <QLabel>
#include <QMoveEvent>
#include <QPushButton>
#include <QColor>

TrasparentWin::TrasparentWin(QWidget *parent)
:QWidget(parent)
,second_wnd_(nullptr)
,switch_(false)
{
    setFixedSize(400, 400);
    setObjectName("main_window");
    CreateSecondWidget();
    auto switch_button = new QPushButton(this);
    switch_button->move(200, 200);
    switch_button->setText("switch button");
    connect(switch_button, SIGNAL(clicked(bool)), this, SLOT(OnSwitch(bool)));
    setStyleSheet("QWidget#main_window{background-color:gray;}");
}

TrasparentWin::~TrasparentWin()
{

}

void TrasparentWin::CreateSecondWidget()
{
    second_wnd_ = new QWidget(this);
    second_wnd_->setObjectName("second_wnd");
    //second_wnd_->setStyleSheet("QWidget#second_wnd{background-color:gray;}");
    second_wnd_->setWindowFlags(second_wnd_->windowFlags() | Qt::Window | Qt::FramelessWindowHint);
    second_wnd_->setAttribute(Qt::WA_DontCreateNativeAncestors);
    second_wnd_->setAttribute(Qt::WA_NativeWindow);
    second_wnd_->setFixedSize(100, 100);
    auto second_layout = new QHBoxLayout();
    auto text_label = new QLabel();
    text_label->setText("Second Window");
    text_label->setFixedSize(50, 20);
    second_layout->addWidget(text_label, 0, Qt::AlignVCenter);
    second_wnd_->setLayout(second_layout);
    second_wnd_->setVisible(true);
    second_wnd_->setAutoFillBackground(true);
}

void TrasparentWin::moveEvent(QMoveEvent *e)
{
    if (second_wnd_)
    {
        second_wnd_->move(e->pos());
    }
}

void TrasparentWin::OnSwitch(bool checked)
{
    switch_ = !switch_;
    if (switch_)
    {
        QPalette bgpal = second_wnd_->palette();
        bgpal.setColor (QPalette::Background, QColor (255, 255 , 0, 255));
        second_wnd_->setPalette(bgpal);
    }
    else
    {
        QPalette bgpal = second_wnd_->palette();
        bgpal.setColor (QPalette::Background, Qt::transparent);
        second_wnd_->setPalette(bgpal);
    }
}

I firstly click switch_button that second_wnd background color is yellow ,then I secondly click swith_button that second_wnd background color is dark,however, that's not my intention. because secondly click should do execute below code:

QPalette bgpal = second_wnd_->palette();
bgpal.setColor (QPalette::Background, Qt::transparent);
second_wnd_->setPalette(bgpal);

why second_wnd background is not transparent?? how can I do it that repeated transparency switch to non-transparency

您应该手动启用小部件透明度:

second_wnd_->setAttribute(Qt::WA_TranslucentBackground, true);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM