【问题标题】:Linebreak in QTableViewQTableView 中的换行
【发布时间】:2018-07-26 18:48:29
【问题描述】:

我的 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 中完成。 The second problem is, that when selecting a row with a widget in it the blue highlighting doesn't apply to the cell.另一个问题是 resizeRowsToContents() 方法没有考虑这个小部件的高度。

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

【问题讨论】:

    标签: python qt pyqt pyqt5 qtableview


    【解决方案1】:

    实现此任务的一种方法是使用 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_())
    

    【讨论】:

    • 实际上有一个问题:如果我调用resizeColumnsToContents(),文本会被截断,并且列会缩小到可能的最小尺寸。我通过删除 doc.setTextWidth(opt.rect.width()) 行来解决这个问题。
    • 在我的解决方案中,我调用w.verticalHeader().setSectionResizeMode(QHeaderView.ResizeToContents) 而不是调用resizeColumnsToContents(),因为它会自动更新大小,我不需要随时调用它。
    猜你喜欢
    • 1970-01-01
    • 2014-07-11
    • 1970-01-01
    • 2011-08-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多