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