我正在(成功地)将某些图像设置为主窗口的背景,并试图强加到图像的大小,但是结果是某种奇怪的形式。我的代码:
main.cpp
#include "mainwindow.h"
#include <QApplication>
int main(int argc, char *argv[]){
QApplication a(argc, argv);
MainWindow w;
w.show();
return a.exec();
}
主窗口
#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
QPixmap bkgnd("background.jpg");
if (!bkgnd.isNull())
{
bkgnd = bkgnd.scaled(this->size() );
QPalette palette;
palette.setBrush(QPalette::Background, bkgnd);
this->setPalette(palette);
this->setMaximumSize (bkgnd.height (),bkgnd.width ());
this->setMinimumSize (bkgnd.height (),bkgnd.width ());
}
}
MainWindow::~MainWindow()
{
delete ui;
}
主窗口
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QLabel>
QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACE
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow(QWidget *parent = nullptr);
~MainWindow();
private:
Ui::MainWindow *ui;
};
#endif // MAINWINDOW_H
但是它的大小仍然不正确。
最佳答案
不清楚要做什么,代码写得毫无意义
bkgnd = bkgnd.scaled(this->size() );
.....
this->setMaximumSize (bkgnd.height (),bkgnd.width ());
this->setMinimumSize (bkgnd.height (),bkgnd.width ());
这是一个简单的示例,添加枚举Qt::IgnoreAspectRatio
#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
QPixmap bkgnd("background.jpg");
if (!bkgnd.isNull())
{
bkgnd = bkgnd.scaled(this->size(), Qt::IgnoreAspectRatio);
QPalette palette;
palette.setBrush(QPalette::Background, bkgnd);
this->setPalette(palette);
}
}
或者你可以只使用
css
setStyleSheet
setStyleSheet("background-image: url(background.jpg);");
关于c++ - 如何设置与背景图片大小相对应的窗口大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61836679/