PyQt / Qt,带有自定义委托的表视图使用省略号作为文本溢出单元格
PyQt / Qt, tableview with custom delegate to use ellipsis for text overflowing cell
没有自定义委托一切正常:
但我的 tableview 显示搜索结果,部分文本需要加粗以指示它与搜索查询匹配的位置。
一旦我使用委托使 html 标签工作,溢出单元格的文本不会被剪裁并替换为省略号:
这是我的代表:
class HTMLDelegate(QStyledItemDelegate):
def __init__(self, parent=None):
super().__init__()
self.doc = QTextDocument(self)
def paint(self, painter, option, index):
painter.save()
options = QStyleOptionViewItem(option)
self.initStyleOption(options, index)
self.doc.setHtml(options.text)
options.text = ""
style = QApplication.style() if options.widget is None \
else options.widget.style()
style.drawControl(QStyle.CE_ItemViewItem, options, painter)
ctx = QAbstractTextDocumentLayout.PaintContext()
if option.state & QStyle.State_Selected:
ctx.palette.setColor(QPalette.Text, option.palette.color(
QPalette.Active, QPalette.HighlightedText))
textRect = style.subElementRect(QStyle.SE_ItemViewItemText, options)
#textRect.adjust(0, 0, 0, 0)
painter.translate(textRect.topLeft())
self.doc.documentLayout().draw(painter, ctx)
painter.restore()
def sizeHint(self, option, index):
return QSize(self.doc.idealWidth(), self.doc.size().height())
另外如果我要添加行
self.doc.setTextWidth(option.rect.width())
它会将文本剪切到另一行(我增加了行高来显示它):
painter.setClipRect(textRect.translated(-textRect.topLeft()))
我以为我的委托中有它,它在这里的所有其他答案中都有,它正确地进行了剪裁,虽然没有花哨的省略号,但我想没关系。
我之前假设我必须启用一些值才能获得剪裁省略号,但我开始看到它可能比这复杂得多,我可能实际上需要根据区域矩形编辑文本本身 - vs在调整每一列的大小或一些东西时采取并调整文本宽度
哦,我多么希望他们可以选择使用默认委托
启用html富文本
没有自定义委托一切正常:
但我的 tableview 显示搜索结果,部分文本需要加粗以指示它与搜索查询匹配的位置。
一旦我使用委托使 html 标签工作,溢出单元格的文本不会被剪裁并替换为省略号:
这是我的代表:
class HTMLDelegate(QStyledItemDelegate):
def __init__(self, parent=None):
super().__init__()
self.doc = QTextDocument(self)
def paint(self, painter, option, index):
painter.save()
options = QStyleOptionViewItem(option)
self.initStyleOption(options, index)
self.doc.setHtml(options.text)
options.text = ""
style = QApplication.style() if options.widget is None \
else options.widget.style()
style.drawControl(QStyle.CE_ItemViewItem, options, painter)
ctx = QAbstractTextDocumentLayout.PaintContext()
if option.state & QStyle.State_Selected:
ctx.palette.setColor(QPalette.Text, option.palette.color(
QPalette.Active, QPalette.HighlightedText))
textRect = style.subElementRect(QStyle.SE_ItemViewItemText, options)
#textRect.adjust(0, 0, 0, 0)
painter.translate(textRect.topLeft())
self.doc.documentLayout().draw(painter, ctx)
painter.restore()
def sizeHint(self, option, index):
return QSize(self.doc.idealWidth(), self.doc.size().height())
另外如果我要添加行
self.doc.setTextWidth(option.rect.width())
它会将文本剪切到另一行(我增加了行高来显示它):
painter.setClipRect(textRect.translated(-textRect.topLeft()))
我以为我的委托中有它,它在这里的所有其他答案中都有,它正确地进行了剪裁,虽然没有花哨的省略号,但我想没关系。 我之前假设我必须启用一些值才能获得剪裁省略号,但我开始看到它可能比这复杂得多,我可能实际上需要根据区域矩形编辑文本本身 - vs在调整每一列的大小或一些东西时采取并调整文本宽度
哦,我多么希望他们可以选择使用默认委托
启用html富文本