我正在尝试通过pyside设置QGridLayout小部件的背景图像(与应用程序位于同一文件夹中)无济于事我查看了有关样式表的所有tuts,docs和论坛帖子但仍然我无法弄清楚我做错了什么。
from PySide.QtCore import *
from PySide.QtGui import *
import sys
class Main(QWidget):
def __init__(self, parent=None):
super(Main, self).__init__(parent)
j = 0
pos = [(0, 0), (0, 1), (0, 2), (0, 3),
(1, 0), (1, 1), (1, 2), (1, 3),
(2, 0), (2, 1), (2, 2), (2, 3),
(3, 0), (3, 1), (3, 2), (3, 3),
(4, 0), (4, 1), (4, 2), (4, 3),
(5, 0), (5, 1), (5, 2), (5, 3)]
grid = QGridLayout(self)
items = ["one", "Two", 'Three','four','five']
for e in items:
picture = ImageLabel("Book.png", self)
picture.name = e
picture.setFixedSize(128,128)
picture.mousepos = str(picture.pos())
picture.imageClicked.connect(self.anotherSlot)
grid.addWidget(picture, pos[j][0], pos[j][1])
j = j + 1
picture.setToolTip('This is' + str(e) + ' widget')
picture.imageHovered.connect(self.Item_Hovered)
self.setStyleSheet("QGridLayout {background-image: url(./image.jpg) }");
def anotherSlot(self):
sender = self.sender()
print "I clicked item " + str(sender.name)
def Item_Hovered(self):
sender = self.sender()
print "I'm Hovering over " + str(sender.name)
class ImageLabel(QLabel):
imageClicked = Signal(str) # can be other types (list, dict, object...)
imageHovered = Signal(str)
imageLeave = Signal(str)
def __init__(self, image, parent=None):
super(ImageLabel, self).__init__(parent)
self.setPixmap(image)
# self.setMouseTracking(True)
def mousePressEvent(self, event):
print "from ImageLabel.mousePressEvent()"
self.imageClicked.emit("Image Clicked")
def enterEvent(self, event):
print "from ImageLabel.enterEvent()"
self.imageHovered.emit("Hovering")
def leaveEvent(self, event):
print "from ImageLabel.leaveEvent()"
self.imageLeave.emit("Hovering No More")
a = QApplication([])
m = Main()
m.show()
sys.exit(a.exec_())
任何建议都将受到赞赏。
答案 0 :(得分:1)
即使它起作用你也不会得到预期的结果,我实现正确背景颜色的唯一方法就是重写paintEvent
tile = QtGui.QPixmap("x.png")
def paintEvent(self, pe):
painter = QtGui.QPainter(self)
painter.drawTiledPixmap(self.rect(), tile)
super(Console, self).paintEvent(pe)
控制台是我的班级class Console(QtGui.QMainWindow):
该示例适用于整个窗口。
我不确定画家构造函数是否可以远离paintEvent
更新:看起来需要在每个QPainter
上创建paintEvent
我发现了一种最简单的方法而不会覆盖paintEvent
palette = QtGui.QPalette()
palette.setBrush(QtGui.QPalette.Background, tile)
self.setPalette(palette)
答案 1 :(得分:1)
检查Qt Stylesheet Reference,它列出了可以使用样式表自定义的小部件。
QGridLayout继承自QLayout,QLayoutItem和QObject。根据参考文献,这些都不能使用样式表进行样式设计。
不要自定义paintEvent处理程序,只需尝试将布局放在QFrame中。 QFrame支持CSS框模型,因此您可以在QFrame上使用background-image属性。
答案 2 :(得分:0)
def paintEvent(self, event):
self.tile= QPixmap("bookshelf.png")
painter = QPainter(self)
painter.drawTiledPixmap(self.rect(), self.tile)
super(Main, self).paintEvent(event)
什么sherpyas代码没有解释(这实际上帮助我理解了paintEvent)是self.tile变量包含实际的pixmap图像,如果在paint变量本身内引用它。
self.tile= QPixmap("bookshelf.png")
会将图像绘制为样式表创建错误的窗口小部件/窗口的背景!