問題描述
我有一個 QListWidget
,我想為列表的每個項目添加邊框底部并為項目設(shè)置背景顏色,我想為特定項目設(shè)置不同的背景顏色.所以我使用 my_list.setStyleSheet("QListWidget::item {border-bottom: 1px solid red; background-color: blue;}")
并將背景顏色設(shè)置為我使用的特定項目 item.setBackground(QtGui.QColor("#E3E3E3"))
問題是我設(shè)置不同顏色的特定項目沒有得到這個顏色.
您不能在小部件上使用樣式表和樣式設(shè)置的組合——樣式表將覆蓋單個項目的任何設(shè)置.例如,以下代碼在每個項目上使用 setBackground
來更改背景顏色.
從 PyQt5.QtGui 導(dǎo)入 *從 PyQt5.QtWidgets 導(dǎo)入 *顏色= ['#7fc97f','#beaed4','#fdc086','#ffff99','#386cb0','#f0027f','#bf5b17','#666666']類主窗口(QMainWindow):def __init__(self, *args, **kwargs):super(MainWindow, self).__init__(*args, **kwargs)w = QListWidget()對于范圍內(nèi)的 n (8):i = QListWidgetItem('%s' % n)i.setBackground(QColor(顏色[n]))w.addItem(i)self.setCentralWidget(w)自我展示()應(yīng)用程序 = QApplication([])w = 主窗口()app.exec_()
結(jié)果輸出:
但是,如果我們在結(jié)果中添加樣式表行(第二個只有底部邊框):
很遺憾,無法設(shè)置項目的邊框和顏色.但是,您可以做的就是插入一個自定義小部件作為列表項,或者
使用委托的方法是定義一個 paint
方法,該方法接受一個 QPainter
對象(您使用它來進(jìn)行實際繪圖),一個 option
參數(shù)包含項目的矩形(相對于父窗口小部件)和一個 index
,您可以通過它檢索項目數(shù)據(jù).然后,您使用 QPainter 上的方法來繪制您的項目.
在上面的示例中,我們使用它來傳遞項目標(biāo)簽(位置 Qt.DisplayRole
)和十六進(jìn)制顏色(位置 Qt.DisplayRole+1
).ItemDisplayRole 的名稱文檔列出了其他定義的數(shù)據(jù)角色",但在大多數(shù)情況下,您可以忽略這些.
I have a QListWidget
and I want to add border bottom to each item of the list and set a background color to items and I want to set to specific items a different background color.
So I used my_list.setStyleSheet("QListWidget::item { border-bottom: 1px solid red; background-color: blue;}")
and to set background color to specific items I used item.setBackground(QtGui.QColor("#E3E3E3"))
The problem is the specif items that I set a different color don't get this color.
You can't use a combination of stylesheets and style settings on a widget — the stylesheet will override any settings on individual items. For example, the following code uses setBackground
on each item to change the background colour.
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
colors = [ '#7fc97f', '#beaed4', '#fdc086', '#ffff99', '#386cb0', '#f0027f', '#bf5b17', '#666666']
class MainWindow(QMainWindow):
def __init__(self, *args, **kwargs):
super(MainWindow, self).__init__(*args, **kwargs)
w = QListWidget()
for n in range(8):
i = QListWidgetItem('%s' % n)
i.setBackground( QColor(colors[n]) )
w.addItem(i)
self.setCentralWidget(w)
self.show()
app = QApplication([])
w = MainWindow()
app.exec_()
The resulting output:
However, if we add the stylesheet line in the result is (and second with only the bottom border):
Unfortunately, there is no way to set the border and the colour for the items. However, what you can do is either insert a custom widget as the list item, or use an item delegate to draw the item. This gives you complete control over appearance, however you have to handle drawing yourself. Below is an example of doing this with a custom delegate:
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
colors = [ '#7fc97f', '#beaed4', '#fdc086', '#ffff99', '#386cb0', '#f0027f', '#bf5b17', '#666666']
class MyDelegate(QItemDelegate):
def __init__(self, parent=None, *args):
QItemDelegate.__init__(self, parent, *args)
def paint(self, painter, option, index):
painter.save()
# set background color
painter.setPen(QPen(Qt.NoPen))
if option.state & QStyle.State_Selected:
# If the item is selected, always draw background red
painter.setBrush(QBrush(Qt.red))
else:
c = index.data(Qt.DisplayRole+1) # Get the color
painter.setBrush(QBrush(QColor(c)))
# Draw the background rectangle
painter.drawRect(option.rect)
# Draw the bottom border
# option.rect is the shape of the item; top left bottom right
# e.g. 0, 0, 256, 16 in the parent listwidget
painter.setPen(QPen(Qt.red))
painter.drawLine(option.rect.bottomLeft(), option.rect.bottomRight())
# Draw the text
painter.setPen(QPen(Qt.black))
text = index.data(Qt.DisplayRole)
# Adjust the rect (to pad)
option.rect.setLeft(5)
option.rect.setRight(option.rect.right()-5)
painter.drawText(option.rect, Qt.AlignLeft, text)
painter.restore()
class MainWindow(QMainWindow):
def __init__(self, *args, **kwargs):
super(MainWindow, self).__init__(*args, **kwargs)
de = MyDelegate(self)
w = QListWidget()
w.setItemDelegate(de)
for n in range(8):
s = '%s' % n
i = QListWidgetItem()
i.setData(Qt.DisplayRole, s) # The label
i.setData(Qt.DisplayRole+1, colors[n]) # The color
w.addItem(i)
self.setCentralWidget(w)
self.show()
app = QApplication([])
w = MainWindow()
app.exec_()
Which gives the following output:
The approach with delegates is to define a paint
method, which accepts a QPainter
object (with which you do the actual drawing), an option
parameter containing the rectangle of the item (relative to the parent widget) and an index
through which you can retrieve the item data. You then use the methods on the QPainter to draw your item.
In the example above we use this to pass in both the item label (at position Qt.DisplayRole
) and the color in hex (at position Qt.DisplayRole+1
). The name docs for ItemDisplayRole list the other defined data 'roles', but for most purposes you can ignore these.
這篇關(guān)于為 QListWidget 中的特定項目設(shè)置不同的顏色的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!