#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背景不透明? 如何重复透明切换到非透明度