问题描述
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 ?
推荐答案
QImage
不是小部件.
在许多小部件上,例如QmainWindow
,QLabel
您可以使用
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布局的背景中添加图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!