编辑单元格的默认行为是双击它,但我想向用户显示,他们可以选择一个列表,(我的一些列只有一个值,并且不可编辑),所以我打开了持久性编辑器,但如果行太多,那就太慢了。
所以我转向重新实现mousePressEvent并在用户右键单击单元格时显示组合框,但没有任何视觉提示告诉他们可以右键单击哪个单元格。 (我知道也许我可以改变那个细胞的bg颜色)
但我可以实现这样的目标吗?在单元格的右下方颜色处绘制一个黑色三角形,表示可以右键单击它?
喜欢excel的这张图片吗?
答案 0 :(得分:1)
您可以使用QStyleItemDelegate,如下所示:
#!/usr/bin/env python
#-*- coding:utf-8 -*-
import sys
from PyQt4 import QtCore, QtGui
class StyledItemDelegateTriangle(QtGui.QStyledItemDelegate):
def __init__(self, parent=None):
super(StyledItemDelegateTriangle, self).__init__(parent)
def paint(self, painter, option, index):
super(StyledItemDelegateTriangle, self).paint(painter, option, index)
polygonTriangle = QtGui.QPolygon(3)
polygonTriangle.setPoint(0, QtCore.QPoint(option.rect.x()+5, option.rect.y()))
polygonTriangle.setPoint(1, QtCore.QPoint(option.rect.x(), option.rect.y()))
polygonTriangle.setPoint(2, QtCore.QPoint(option.rect.x(), option.rect.y()+5))
painter.save()
painter.setRenderHint(painter.Antialiasing)
painter.setBrush(QtGui.QBrush(QtGui.QColor(QtCore.Qt.darkGreen)))
painter.setPen(QtGui.QPen(QtGui.QColor(QtCore.Qt.darkGreen)))
painter.drawPolygon(polygonTriangle)
painter.restore()
class MyWindow(QtGui.QTableWidget):
def __init__(self, parent = None):
super(MyWindow, self).__init__(parent)
self.styledItemDelegateTriangle = StyledItemDelegateTriangle(self)
self.setItemDelegate(self.styledItemDelegateTriangle)
self.setRowCount(2)
self.setColumnCount(3)
if __name__ == "__main__":
app = QtGui.QApplication(sys.argv)
app.setApplicationName('MyWindow')
main = MyWindow()
main.resize(333, 111)
main.show()
sys.exit(app.exec_())