Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/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));
            message_text->setTextInteractionFlags(Qt::TextSelectableByMouse);
    
            std::string time = DateTimeStrFormat("%d %B %Y %H:%M", msg.time);
            auto* message_time = new QLabel(QString::fromStdString(time));
            message_time->setAlignment(Qt::AlignRight);
            message_time->setStyleSheet("QLabel { color : #bdbdbd; }");
    
            message_layout->addWidget(message_text);
            message_layout->addWidget(message_time);
            message_layout->setSizeConstraint( QLayout::SetFixedSize );
            message_widget->setLayout(message_layout);
    
            if (sendingAddress == msg.from) {
                message_layout->setAlignment(Qt::AlignRight);
                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->addItem(item);
            ui->message_widget->setItemWidget(item, message_widget);
        }
    

  • Lifetime Qt Champion

    Hi
    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