Important: Please read the Qt Code of Conduct -

Align QListWidgetItem's QWidget to left or right depending

  • I have an interface to display a two-way conversation between, I want messages from the UI to be aligned to the right and external messages to be aligned to the left. I've not been able to align messages from the UI to the right hand side.

    Below is the code I have for creating and adding the messages. The messages are held in a QListWidget to allow them to be displayed top down, this is called ui->message_widget. This holds a series of QListWidgetItem, each QListWidgetItem has a QWidget set, it is the QWidget that holds the actual contents. The contents are two QLabels, one for the message and the other for the time stamp.

        for (auto& msg : messages) {
            auto* message_widget = new QWidget();
            auto* message_layout = new QVBoxLayout(message_widget);
            auto* message_text = new QLabel(QString::fromStdString(msg.text));
            std::string time = DateTimeStrFormat("%d %B %Y %H:%M", msg.time);
            auto* message_time = new QLabel(QString::fromStdString(time));
            message_time->setStyleSheet("QLabel { color : #bdbdbd; }");
            message_layout->setSizeConstraint( QLayout::SetFixedSize );
            if (sendingAddress == msg.from) {
                message_widget->setStyleSheet("QWidget { background: #fff; border-radius: 5px; }");
            } else {
                message_widget->setStyleSheet("QWidget { background: #effdde; border-radius: 5px; }");
            auto* item = new QListWidgetItem();
            item->setSizeHint( message_widget->sizeHint() );
            ui->message_widget->setItemWidget(item, message_widget);

  • Lifetime Qt Champion

    What do you get ?
    The labels are left-aligned anyway ?
    Do you use Rich Text?
    If you disable the style sheets, its still not right-aligned ?

Log in to reply