Issue
I want to change alpha of QListWidgetItem background and foreground (text) color. I need this to implement search in the list where items grey out if do not match QLineEdit value. I get item background color (foreground the same way) with:
for row in range(self.mylist.count()):
color = self.mylist.item(row).background().color()
print(color.name())
But always get #000000
. Have checked alpha of color (with color.alpha()
) and it was always 255. When I change color with new alpha and apply it with self.mylist.item(row).setBackground(color)
, background gets black. Probably I get color the wrong way?
Minimal reproducible example (double click on item):
from PyQt5 import QtWidgets
def getColor(self):
for row in range(mylist.count()):
color = mylist.item(row).background().color()
print(color.name())
print(color.alpha())
app = QtWidgets.QApplication([])
mylist = QtWidgets.QListWidget()
item=QtWidgets.QListWidgetItem()
item.setText("test")
mylist.addItem(item)
mylist.show()
mylist.doubleClicked.connect(getColor)
app.exec_()
Solution
The QBrush of the background by default the QListWidgetItem is null so the painting will not be used, that is, the background color is not painted, so the default color is the background color of the view.
In the case of the foreground, the same thing happens, but instead of not painting it, it uses the text color of the view palette.
So if you want to get the background color and text if the QBrush is null then you will have to use the view palette:
from PyQt5 import QtCore, QtWidgets
def getColor(self):
for row in range(mylist.count()):
it = mylist.item(row)
brush = it.background()
if brush.style() == QtCore.Qt.NoBrush:
brush = mylist.palette().base()
color = brush.color()
color.setAlpha(100 if color.alpha() == 255 else 255)
brush.setColor(color)
it.setBackground(brush)
brush = it.foreground()
if brush.style() == QtCore.Qt.NoBrush:
brush = mylist.palette().text()
color = brush.color()
color.setAlpha(100 if color.alpha() == 255 else 255)
brush.setColor(color)
it.setForeground(brush)
app = QtWidgets.QApplication([])
mylist = QtWidgets.QListWidget()
for i in range(5):
item = QtWidgets.QListWidgetItem()
item.setText("test ")
mylist.addItem(item)
mylist.show()
mylist.doubleClicked.connect(getColor)
app.exec_()
Answered By - eyllanesc
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.