想将QWidget上的一个QPushButton旋转,且QWidget是透明背景,QPushButton是不规则窗体。即只显示一个不规则的QPushButton在转。
上网查询发现button不能直接旋转,其中一种方法是放到QGraphicsView中,QGraphicsView可以旋转。
Widget::Widget(QWidget *parent) :
QWidget(parent),
ui(new Ui::Widget)
{
ui->setupUi(this);
setWindowOpacity(1);
scene = new QGraphicsScene(0, 0, 100, 100);
ui->graphicsView->setScene(scene);
ui->graphicsView->setFrameShape(QFrame::NoFrame);
this->setAttribute(Qt::WA_TranslucentBackground); //设置widget透明背景
this->setWindowFlags(Qt::FramelessWindowHint); //去掉Widget边框
QPixmap pix;
pix.load(":/snowIcons/03.png");
QPushButton *btn = new QPushButton(nullptr);
btn->setFixedSize(100, 100 );
btn->setFocusPolicy(Qt::NoFocus);
btn->setEnabled(false);
btn->setAttribute(Qt::WA_TranslucentBackground); //设置button透明
btn->setStyleSheet("border-image: url(:/snowIcons/03.png)"); //设置button的背景图
scene->addWidget(btn);
ui->graphicsView->setAttribute(Qt::WA_TranslucentBackground); //设置QGraphicsView透明背景
ui->graphicsView->setStyleSheet("background: transparent;border:0px");//无边框,背景透明
startTimer(30);
}
Widget::~Widget()
{
delete ui;
}
void Widget::timerEvent(QTimerEvent *e)
{
ui->graphicsView->rotate(20);
}
QGraphicsView上添加QGraphicsScene,在QGraphicsScene上放入button。当QGraphicsView调用rotate()函数时,QGraphicsView本身不旋转,而是内部的scene旋转。
效果最终为一个雪花在不停的转。