注册 登录
编程论坛 QT论坛

qt5如何让背景随窗口大小变化而缩放

纯蓝之刃 发布于 2020-05-22 13:30, 2399 次点击
程序代码:
InstructionHelp::InstructionHelp(QWidget *parent):QDialog(parent)
{
    setWindowFlags(Qt::Window|Qt::WindowTitleHint|Qt::CustomizeWindowHint|Qt::WindowCloseButtonHint);
    //setFixedSize(400,350);
    resize(QSize(300,250));
    setWindowTitle(tr("帮助"));

    //设置背景图案
    QPixmap pixmap_background=QPixmap(":/res/background_sub2.jpg").scaled(this->size());
    QPalette palette(this->palette());
    palette.setBrush(QPalette::Background, QBrush(pixmap_background));
    this->setPalette(palette);
}

如何让背景随窗口大小变化而缩放。
程序代码:
//重载resizeEvent
void InstructionHelp::resizeEvent(QResizeEvent *)
{
    QPixmap pixmap_background=QPixmap(":/res/background_sub2.jpg").scaled(this->size());
    QPalette palette(this->palette());
    palette.setBrush(QPalette::Background, QBrush(pixmap_background));
    this->setPalette(palette);
}

重载resizeEvent不会被触发,或者有没有其他的实现方法
2 回复
#2
fulltimelink2020-06-11 17:22
我这测试是可以的, 构造函数不需要单独设置背景图案,程序启动显示时会自动调用resizeEvent

程序代码:


#ifndef INSTRUCTIONHELP_H
#define INSTRUCTIONHELP_H

#include <QDialog>

class InstructionHelp : public QDialog
{
        Q_OBJECT

    public:
        InstructionHelp(QWidget *parent = nullptr);
        ~InstructionHelp();
    protected:
        void resizeEvent(QResizeEvent *);
};
#endif // INSTRUCTIONHELP_H







#include "instructionhelp.h"

InstructionHelp::InstructionHelp(QWidget *parent)
    : QDialog(parent)
{
    setWindowFlags(Qt::Window|Qt::WindowTitleHint|Qt::CustomizeWindowHint|Qt::WindowCloseButtonHint);
        //setFixedSize(400,350);
        resize(QSize(300,250));
        setWindowTitle(tr("帮助"));
}

InstructionHelp::~InstructionHelp()
{
}

void InstructionHelp::resizeEvent(QResizeEvent *event)
{
    QPixmap pixmap_background=QPixmap(":/img/banner_ly.png").scaled(this->size());
       QPalette palette(this->palette());
       palette.setBrush(QPalette::Background, QBrush(pixmap_background));
       this->setPalette(palette);
    QDialog::resizeEvent(event);
}
#3
fulltimelink2020-06-11 17:24
如果你的res是resource的名字,且你运行是黑屏的话,  你把 :/res/background_sub2.jpg  改为 :/background_sub2.jpg
1