alexandernst
alexandernst

Reputation: 15099

Use rich text in QTableWidgetItem

Is there a way I can use rich text in QTableWidgetItem?

Currently I have this:

widgetItem = QtWidgets.QTableWidgetItem()
widget = QtWidgets.QWidget()
widgetText =  QtWidgets.QLabel("<b>foo bar</b>")
widgetLayout = QtWidgets.QHBoxLayout()
widgetLayout.addWidget(widgetText)
widgetLayout.setSizeConstraint(QtWidgets.QLayout.SetFixedSize)
widget.setLayout(widgetLayout)
widgetItem.setSizeHint(widget.sizeHint())
self.tablewidget.setCellWidget(0, 0, widget)
self.tablewidget.resizeColumnsToContents()

But nothing shows it my table widget.

Upvotes: 1

Views: 1685

Answers (1)

eyllanesc
eyllanesc

Reputation: 244162

When you create a QTableWidget you must set the number of rows and columns, for example:

self.tablewidget = QtWidgets.QTableWidget(2, 2, self)

Or we can set it later using the setRowCount() and setColumnCount() functions:

self.tablewidget = QtWidgets.QTableWidget(self)
self.tablewidget.setRowCount(10)
self.tablewidget.setColumnCount(5)

But if you do not use the above form the widget will not be displayed, in your case the label.

Also it is not necessary to use QTableWidgetItem, as I show below:

import sys
from PyQt5 import QtWidgets


if __name__ == "__main__":
    app = QtWidgets.QApplication(sys.argv)

    tablewidget = QtWidgets.QTableWidget(4, 4)
    widget = QtWidgets.QWidget()
    widgetText =  QtWidgets.QLabel("<b>foo bar</b>")
    widgetLayout = QtWidgets.QHBoxLayout()
    widgetLayout.addWidget(widgetText)
    widgetLayout.setSizeConstraint(QtWidgets.QLayout.SetFixedSize)
    widget.setLayout(widgetLayout)
    tablewidget.setCellWidget(0, 0, widget)
    tablewidget.resizeColumnsToContents()
    tablewidget.show()

    sys.exit(app.exec_())

Output:

enter image description here

Upvotes: 3

Related Questions