Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

QTableWidget/QTableView "word wrap" behavior, but without words (no spaces)?



  • Hello,

    I have a QTableWidget that currently is only using 1 column, and is set to stretch its columns to fit the entire widget, that I am filling with QTableWidgetItems constructed from QStrings . The behavior I desire is to have the text in each cell continue on the next line once it reaches the end of the cell so that the entire string is visible and the cell does not use ellipsis and omit the rest of the string. Additionally, I want this property to be in display only, meaning that no modifications are actually made to the QString (i.e. no line-break insertions) itself and it is simply shown in this fashion. At first I thought the word wrap option of QTableWidget would handle this as shown below:

    This is how I setup and fill the widget

    int rows = 1;
        ui->testWidget->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
        ui->testWidget->setColumnCount(1);
        ui->testWidget->setRowCount(rows);
       // Word wrap in on by default
    
        QString readString = "This sentence has spaces between words as one would expect";
        for (int r = 0; r < rows; r++) {
            for (int column = 0; column < 1; column++) {
                QTableWidgetItem* item = new QTableWidgetItem(readString);
                ui->testWidget->setItem(r, 0, item);
            }
        }
    
        ui->testWidget->resizeRowsToContents();
    

    which works great at first glance:
    Wrap with spaces

    but I came to learn that this property does strictly mean word wrap, as when I use a string that doesn't have spaces (which will be the case 100% of the time for these cells) I get:
    No wrap with no spaces

    In theory I could calculate where to insert '\n' characters and then temporarily remove them right when the user double-clicks the cell to edit it and remove them permanently whenever the cell data is accessed by the rest of the program (though they may be ignored from what I've read elsewhere), but this would be very clunky and is highly undesirable.

    Is there any way I can force the cell data to wrap even if is is all one "word" while keeping the actual QString unchanged?