Cloud around the text in QTextEdit

No problem :slight_smile:

To show the time, you probably want to send it in the message payload. So your send method becomes (add from time import time at the top). The time.time() method returns the current unix timestamp.

    def invia_messaggio(self):
        self.pubblica(
            {
                "name": self.nome,
                "message": self.input_per_il_messaggio.text(),
                "time": time(),
            }
        )
        self.input_per_il_messaggio.clear()

When you create the messages in the model, you need to pass this through as a 3rd parameter.

                    self.modello.add_message(
                        io, message_str, self.messaggio.get("time")
                    )

…and update add_message to accept that 3rd timestamp parameter.

    def add_message(self, who, text, timestamp):
        if text:
            self.messages.append((who, text, timestamp))
            self.layoutChanged.emit()

So, at this point the time data is in your model. You just need to –

  1. Update the paint method to draw the time in the bubble.
  2. Update the sizeHint method to add a bit of padding to provide space for the time.

First for sizeHint update the data call to unpack the 3rd value. We can discard it (using _) because we don’t need it to calculate the height. We’re just going to add 20 pixels – the time height is always the same.

    def sizeHint(self, option, index):
        _, text, _ = index.model().data(index, Qt.DisplayRole)
        # ... keep the rest the same.
        return textrect.size() + QSize(0, 20)

In the paint we unpack the timestamp from the data returned from the model.

    def paint(self, painter, option, index):
        painter.save()
        user, text, timestamp = index.model().data(index, Qt.DisplayRole)
        # ... add timestamp param, keep the rest the same until...

        toption = QTextOption()
        toption.setWrapMode(QTextOption.WrapAtWordBoundaryOrAnywhere)
       
        # draw the timestamp
        font = painter.font()

        font.setPointSize(7)
        painter.setFont(font)
        painter.setPen(Qt.black)
        time_str = datetime.fromtimestamp(timestamp).strftime("%Y-%m-%d %H:%M:%S")
        painter.drawText(textrect.bottomLeft() + QPoint(0, 5), time_str)

        doc = QTextDocument(text)

        # ...continues as before.

textrect.bottomLeft() is the bottom left of our text rectangle, into which we draw our message. By taking that as our starting position for our timestamp, we’ll align directly under it. We add 5px vertically for some padding.

This is the same pattern for adding anything to model views – add it to the model, update the paint & sizeHint methods to draw and create space.

The DeprecationWarning is because we’re passing a float value where an int is expected. It’s a new warning in Python 3.8. You can just convert to an int explicitly by wrapping in int(), e.g.

textrect.setHeight(int(doc.size().height()))