python-3.x - PyQt5 - 在 MainWindow 布局的背景中添加图像

标签 python-3.x qwidget pyqt5 qimage qlayout

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

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

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 中显示为背景?

最佳答案

The QVBoxLayout class lines up widgets vertically.



documentation QVBoxLayout
QImage不是小部件。

在许多小部件上,例如QmainWindow , QLabel您可以使用
widget.setStyleSheet(„ background-image: url(backgound.png);“)

在我的机器上,这不适用于 QWidget .在这种情况下,您可以使用以下代码重写:
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_())

关于python-3.x - PyQt5 - 在 MainWindow 布局的背景中添加图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35422490/

相关文章:

c++ - 在 Qt 小部件中显示 cmd.exe 窗口

python - QScrollArea.ensureWidgetVisible 方法不显示目标小部件

python - PyQt5-Python | QApplication.setStyle 不起作用

python - 当我按下另一个 QWidget 中的按钮时,我想在 QPixmap 中设置 path_to_photo

python - 如何在 python 中关闭 udp 套接字

c++ - 对象的所有权 - 哪个小部件应该删除它?

python - 如何返回不带引号的字符串 Python 3

c++ - Qt:enterEvent 和 leaveEvent 不起作用

Python3 无穷大/NaN : Decimal vs. float

python Pandas : Count of datetime items between dateindex and next dateindex