python - QTableView 中的换行符

标签 python qt pyqt pyqt5 qtableview

我的 GUI 中有一个 QTableView,其中我想要一些表格单元格,我可以使用类似 \n 的内容插入换行符。或<br> 。 到目前为止,我已尝试将 QLabel 设置为 IndexWidget:

l = QLabel(val[2])
self.setRowHeight(i, int(l.height() / 8))
l.setAutoFillBackground(True)
self.setIndexWidget(QAbstractItemModel.createIndex(self.results_model, i, 2), l)

这种方法的问题是代码不是很干净,如果没有这段代码用小部件替换单元格,就不能在 AbstractTableModel 中完成。第二个问题是,当选择其中包含小部件的行时,蓝色突出显示不适用于该单元格。另一个问题是 resizeRowsToContents() 方法没有考虑此小部件的高度。

任何想法将不胜感激,谢谢!

最佳答案

实现此任务的一种方法是使用 HtmlDelegate,在这种情况下,换行符将由 <br> 给出。 :

import sys

from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *

class HTMLDelegate(QStyledItemDelegate):
    def paint(self, painter, option, index):
        opt = QStyleOptionViewItem(option)
        self.initStyleOption(opt, index)

        painter.save()
        doc = QTextDocument()
        doc.setHtml(opt.text)
        opt.text = "";
        style = opt.widget.style() if opt.widget else QApplication.style()
        style.drawControl(QStyle.CE_ItemViewItem, opt, painter)
        painter.translate(opt.rect.left(), opt.rect.top())
        clip = QRectF(0, 0, opt.rect.width(), opt.rect.height())
        doc.drawContents(painter, clip)
        painter.restore()

    def sizeHint(self, option, index ):
        opt = QStyleOptionViewItem(option)
        self.initStyleOption(opt, index)
        doc = QTextDocument()
        doc.setHtml(opt.text);
        doc.setTextWidth(opt.rect.width())
        return QSize(doc.idealWidth(), doc.size().height())

if __name__ == '__main__':
    app = QApplication(sys.argv)
    w = QTableView()
    model = QStandardItemModel(4, 6)
    delegate = HTMLDelegate()
    w.setItemDelegate(delegate)
    w.setModel(model)
    w.verticalHeader().setSectionResizeMode(QHeaderView.ResizeToContents)
    w.show()
    sys.exit(app.exec_())

enter image description here

关于python - QTableView 中的换行符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48816961/

相关文章:

python - 多线程Python请求

python - Pandas 中一列的值作为列,同时保持最后更新

c++ - 如何将我的 makefile 项目导入 QtCreator?

qt - applescript-QuickTime 7音频(WAV)导出

python - PyQt 启用/禁用 QComboBox 中的元素

python - 在 Python 中将日期转换为日期时间

C++、正则表达式

qt - 我可以为多个信号设置一个插槽吗?

python - PyQt Qthread自动重启

python - set_axis() 获得参数 'axis' 的多个值