除了使用QIcon之外,如何将DecorationRole形状更改为圆形?
How to change DecorationRole shape to circle,except for using QIcon?
我想为QTableView添加一些圆形的DecorationRole,但是这似乎是不可能的。
import sys
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtCore import Qt
class TableModel(QtCore.QAbstractTableModel):
def __init__(self, data):
super().__init__()
self._data = data
def data(self, index, role):
if role == Qt.DecorationRole:
return QtGui.QColor('red') #change shape to circle
if role == Qt.DisplayRole:
return 'hi'
...
一个可能的解决方案是创建一个 QPixmap:
import sys
from PyQt5 import QtCore, QtGui, QtWidgets
class TableModel(QtCore.QAbstractTableModel):
def data(self, index, role):
if role == QtCore.Qt.DecorationRole:
pixmap = QtGui.QPixmap(96, 96)
pixmap.fill(QtCore.Qt.transparent)
painter = QtGui.QPainter(pixmap)
painter.setRenderHint(QtGui.QPainter.Antialiasing)
painter.setBrush(QtGui.QColor("red"))
painter.drawEllipse(pixmap.rect())
painter.end()
return QtGui.QIcon(pixmap)
if role == QtCore.Qt.DisplayRole:
return "hi"
def rowCount(self, parent=QtCore.QModelIndex()):
if parent.isValid():
return 0
return 4
def columnCount(self, parent=QtCore.QModelIndex()):
if parent.isValid():
return 0
return 4
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
view = QtWidgets.QTableView()
model = TableModel()
view.setModel(model)
view.resize(640, 480)
view.show()
sys.exit(app.exec_())
我想为QTableView添加一些圆形的DecorationRole,但是这似乎是不可能的。
import sys
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtCore import Qt
class TableModel(QtCore.QAbstractTableModel):
def __init__(self, data):
super().__init__()
self._data = data
def data(self, index, role):
if role == Qt.DecorationRole:
return QtGui.QColor('red') #change shape to circle
if role == Qt.DisplayRole:
return 'hi'
...
一个可能的解决方案是创建一个 QPixmap:
import sys
from PyQt5 import QtCore, QtGui, QtWidgets
class TableModel(QtCore.QAbstractTableModel):
def data(self, index, role):
if role == QtCore.Qt.DecorationRole:
pixmap = QtGui.QPixmap(96, 96)
pixmap.fill(QtCore.Qt.transparent)
painter = QtGui.QPainter(pixmap)
painter.setRenderHint(QtGui.QPainter.Antialiasing)
painter.setBrush(QtGui.QColor("red"))
painter.drawEllipse(pixmap.rect())
painter.end()
return QtGui.QIcon(pixmap)
if role == QtCore.Qt.DisplayRole:
return "hi"
def rowCount(self, parent=QtCore.QModelIndex()):
if parent.isValid():
return 0
return 4
def columnCount(self, parent=QtCore.QModelIndex()):
if parent.isValid():
return 0
return 4
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
view = QtWidgets.QTableView()
model = TableModel()
view.setModel(model)
view.resize(640, 480)
view.show()
sys.exit(app.exec_())