0
#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);
}
}
我首先單擊switch_button是second_wnd背景顏色爲黃色,然後我點擊其次是swith_button背景second_wnd顏色深,然而,這不是我的本意。因爲其次點擊應該執行以下代碼:如何切換不透明到透明背景的子窗口
QPalette bgpal = second_wnd_->palette();
bgpal.setColor (QPalette::Background, Qt::transparent);
second_wnd_->setPalette(bgpal);
爲什麼second_wnd背景不透明? 我怎麼能做到這一點的是重複的透明度切換到非透明
@PazrFalcon我tryied,但我首先單擊switch_button,second_wnd無法改變的背景。 – xyCoder
我不明白你的問題。爲什麼WA_TranslucentBackground不起作用? – RazrFalcon
在我的情況下,我經常使用WA_TranslucentBackground true或false,沒有工作 – xyCoder