PyQt5 - 在 MainWindow 布局的背景中添加图像 [英] PyQt5 - Add image in background of MainWindow layout

查看:46
本文介绍了PyQt5 - 在 MainWindow 布局的背景中添加图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

PyQt5 新手...这是一个非常基本的问题.

New to PyQt5... Here is a very basic question.

我想在小部件的布局中添加图像.这个小部件是我的应用程序的主窗口/根小部件.我使用以下代码,但收到错误消息.

I would like to add an image inside the layout of a widget. This widget is the Main Window / root widget of my application. I use the following code, but I get an error message.

import sys

from PyQt5.QtGui import QImage
from PyQt5.QtWidgets import *

class MainWindow(QWidget):

    def __init__(self):

       super().__init__()

       self.setGeometry(300,300,300,220)
       self.setWindowTitle("Hello !")

       oImage = QImage("backgound.png")

       oLayout = QVBoxLayout()
       oLayout.addWidget(oImage)

       self.setLayout(oLayout)

       self.show()

if __name__ == "__main__":

    app = QApplication(sys.argv)

    oMainwindow = MainWindow()

    sys.exit(app.exec_())


TypeError: QBoxLayout.addWidget(QWidget, int stretch=0, Qt.Alignment alignment=0): argument 1 has unexpected type 'QImage'

显然 QLayoutWidget 不接受 QImage 作为输入.是否有解决方法让图像在 QWidget 中显示为背景?

Apparently a QLayoutWidget does not accept a QImage as an input. Is there a workaround to have an image appear as a brackground in a QWidget ?

推荐答案

QVBoxLayout 类垂直排列小部件.

The QVBoxLayout class lines up widgets vertically.

文档 QVBoxLayout

QImage 不是小部件.

在许多小部件上,例如QmainWindowQLabel可以使用

on many widgets e.g. QmainWindow, QLabel you can use

widget.setStyleSheet(„ background-image: url(backgound.png);")

在我的机器上,这不适用于 QWidget.在这种情况下,您可以使用以下代码重写:

on my machine this doesn't work with QWidget. In this case you can use the following rewrite of your code:

import sys
from PyQt5.QtCore import QSize
from PyQt5.QtGui import QImage, QPalette, QBrush
from PyQt5.QtWidgets import *

class MainWindow(QWidget):
    def __init__(self):
       QWidget.__init__(self)
       self.setGeometry(100,100,300,200)

       oImage = QImage("test.png")
       sImage = oImage.scaled(QSize(300,200))                   # resize Image to widgets size
       palette = QPalette()
       palette.setBrush(QPalette.Window, QBrush(sImage))                        
       self.setPalette(palette)

       self.label = QLabel('Test', self)                        # test, if it's really backgroundimage
       self.label.setGeometry(50,50,200,50)

       self.show()

if __name__ == "__main__":

    app = QApplication(sys.argv)
    oMainwindow = MainWindow()
    sys.exit(app.exec_())

这篇关于PyQt5 - 在 MainWindow 布局的背景中添加图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆