QStyledItemDelegate's Option Is Not Updating
Solution 1:
When the size hint of an index changes, you need to emit MessageDelegate.sizeHintChanged
to let the layout manager of the items know that it needs to redistribute the items. In this case the height of the items only changes when the window is resized, so what you could do is to emit a (custom) signal in Dialog.resizeEvent
and connect it to MessageDelegate.sizeHintChanged
. For this Dialog
would need to be modified according to something like this
from PyQt5.QtCore import pyqtSignal, QModelIndex
class Dialog(QMainWindow):
# custom signal for signalling when window is resized
width_changed = pyqtSignal()
def __init__(self):
... as before ...
self.messages = QListView()
delegate = MessageDelegate()
self.messages.setItemDelegate(delegate)
# Connect custom signal to delegate.sizeHintChanged.
# This signal expects a ModelIndex for which we take the root, i.e. QModelIndex()
self.width_changed.connect(lambda : delegate.sizeHintChanged.emit(QModelIndex()))
.... rest as before ....
def resizeEvent(self, event):
global window_width
super(Dialog, self).resizeEvent(event)
window_width = self.size().width()
# emit the custom signal
self.width_changed.emit()
In the code above I didn't modify anything else in the code, but you could opt to get rid of the global window_width
variable by modifying the custom signal to emit the new width and create a slot in MessageDelegate
to assign the new width to an instance variable.
Solution 2:
Wrapping of item contents is already implemented inside QListView
and can be enabled with self.messages.setWordWrap(True)
. If you use delegate only for text wrapping you dont need it at all.
Post a Comment for "QStyledItemDelegate's Option Is Not Updating"