How to make QListWidget auto-format the Item's text

1k views Asked by At

The code below creates a QTextBrowser populated with 5 lines. Each line is 100+ characters long. To make all the characters (the letters) visible the QTextBrowser reformats the text as soon as the size of the widget is changed. Try to drag the right-bottom corner of the widget to see how QTextBrowser constantly updates the text to keep it in a view.

QTextBrowser:

enter image description here

from PyQt4 import QtCore, QtGui
app=QtGui.QApplication([])

textBrowser = QtGui.QTextBrowser()
for i in range(5):
    textBrowser.insertPlainText('MESSAGE-%04d'%i +'-'*100 + '\n')

textBrowser.show()
app.exec_()

I wonder if QListWidget could be configured to support a "text auto-formating" functionality as well. The code below is exact copy of the one posted above except the QListWidget is now used in place of QTextBrowser. The QListWidget clips the extra characters from view and does nothing in an attempt to reformat the text to make it visible to the user. Is there a way to change this behavior?

QListWidget:

enter image description here

from PyQt4 import QtCore, QtGui
app=QtGui.QApplication([])

listWidget = QtGui.QListWidget()
for i in range(5):
    QtGui.QListWidgetItem('ITEM-%04d '%i+'-'*100, listWidget)

listWidget.show()
app.exec_()

EDITED LATER:

Below is the attempt to use setItemWidget to substitute QListWidgetItem with QTextBrowser. But unfortunately the size of the resulted QTextBrowser is way too large. If there could be a way to fine tune its size it could be a solution:

enter image description here

from PyQt4 import QtCore, QtGui
app=QtGui.QApplication([])

class TextBrowser(QtGui.QTextBrowser):
    def __init__ (self, parent = None):
        super(TextBrowser, self).__init__(parent)

listWidget = QtGui.QListWidget()
for i in range(5):
    item = QtGui.QListWidgetItem('ITEM-%04d '%i+'-'*100, listWidget)
    itemWidget = TextBrowser()
    itemWidget.setText('ITEM-%04d '%i+'-'*100)
    item.setSizeHint(itemWidget.sizeHint())
    listWidget.setItemWidget(item, itemWidget)

listWidget.show()
app.exec_()
0

There are 0 answers