簡體   English   中英

如何將不透明的子窗口切換為透明

[英]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);
    }
}

我先單擊“ second_wnd”背景色為黃色的switch_button,然后再單擊“ second_wnd”背景色為深色的swith_button,但是,這不是我的意圖。 因為第二次單擊應該執行以下代碼:

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

為什么second_wnd背景不透明? 我該怎么做,將重復的透明度切換為不透明

您應該手動啟用小部件透明度:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM