在QTableView单元中绘制可调整的文本

在QTableView单元中绘制可调整的文本

问题描述:

我需要继承我的QTableView的QStyledItemDelegate。更具体地说,我需要修改特定列的显示。此列中的单元格通常包含文本。这里是我的自定义QStyledItemDelegate类的一小部分:在QTableView单元中绘制可调整的文本

elif index.column() == 3: 
    title = index.data() 
    painter.drawText(option.rect, QtCore.Qt.AlignCenter, title) 

但我有一个小问题,当我尝试这样显示。

预计:

Expected

现实:

reality

为了获得预期的图片,我只是做在StyledItemDelegate此列什么。我需要做同样的事情,但使用drawText函数。

你有什么想法吗?

+0

所以不会妄加回答。但我猜你需要设置[wordWrap](http://qt-project.org/doc/qt-4.8/qtableview.html#wordWrap-prop)。 – 2015-02-06 14:02:25

好吧,我发现了一种答案在这里:Word Wrap with HTML? QTabelView and Delegates

它还转换为HTML文本,并允许HTML格式(我需要它太),但我认为它可以很容易地转化为显示简单的文本,与单词换行。

这个片段基本上是为那些谁想要修改的内容和/或在飞行中的内容的格式,通过QStyledItemDelegate:我不熟悉这个工具包

options = QtGui.QStyleOptionViewItemV4(option) 
self.initStyleOption(options, index) 

painter.save() 

doc = QtGui.QTextDocument() 
text_option = QtGui.QTextOption(doc.defaultTextOption()) 
text_option.setWrapMode(QtGui.QTextOption.WordWrap) 
doc.setDefaultTextOption(text_option) 

# Modify the text here. Ex: 
# options.text += "<br><br>" 
doc.setHtml(options.text) 
doc.setTextWidth(options.rect.width()) 

options.text = "" 
options.widget.style().drawControl(QtGui.QStyle.CE_ItemViewItem, options, painter) 

# Center the text vertically 
height = int(doc.documentLayout().documentSize().height()) 
painter.translate(options.rect.left(), options.rect.top() + options.rect.height()/2 - height/2) 

clip = QtCore.QRectF(0, 0, options.rect.width(), options.rect.height()) 
doc.drawContents(painter, clip) 

painter.restore() 
+0

如果您没有使用QTextDocument的特殊要求,您可以尝试QScitinlla [http://www.riverbankcomputing.com/software/qscintilla/download],它是一般编辑的包装,它也可以处理wordwrap,请参阅该API 虚拟无效QsciScintilla :: setWrapMode \t(\t \t WrapMode模式\t)\t [虚,槽]在http://pyqt.sourceforge.net/Docs/QScintilla2/classQsciScintilla.html#ac04428d2f90c36458d68a673f107e40c。 – 2015-02-08 10:11:21