Is it possible to put multiple lines of text in one row of QTableWidget?
Asked
Active
Viewed 2.0k times
3 Answers
6
I can think about 2 ways to force tablewidget to render multi-line text:
Setup QStyledItemDelegate item delegate and render text yourself in the delegates paint method. Here you can find an example of you could do the same thing to a listview.
Another solution would be to set QTextEdit as a cell widget to the table widget via setCellWidget method.
Below is an example for #2:
QTableWidget* tableWidget = new QTableWidget(3, 2, this);
tableWidget->setGeometry(20, 20, 300, 300);
for (int row = 0; row<3; row++)
{
for (int column=0; column<2; column++)
{
QTableWidgetItem *newItem = new QTableWidgetItem(tr("%1 long long long long long long text").arg((row+1)*(column+1)));
tableWidget->setItem(row, column, newItem);
}
QTextEdit *edit = new QTextEdit();
edit->setText(tableWidget->item(row, 0)->text());
tableWidget->setCellWidget(row, 0, edit);
}
hope this helps, regards

Community
- 1
- 1

serge_gubenko
- 20,186
- 2
- 61
- 64
-
1It seems that your link for "QStyledItemDelegate" is broken. A currently working link is this: [QStyledItemDelegate](http://doc.qt.io/qt-5/qstyleditemdelegate.html). The same for "setCellWidget": [QTableWidget::setCellWidget()](http://doc.qt.io/qt-5/qtablewidget.html#setCellWidget). (I would've fixed it by myself but the edit queue seems to be ful...) – Scheff's Cat Jun 09 '17 at 16:56
5
You can also simply use \n to start new line in a cell :-)
For example:
ui->tableWidget->insertRow(i);
QTableWidgetItem *newItem = new QTableWidgetItem("Line 1 \n Line 2");
ui->tableWidget->setItem(0,0,newItem);

Sebastian Dusza
- 2,470
- 2
- 30
- 54
-
5You may want to call ui->tableWidget->resizeRowToContents(i) afterwards, to make sure that the tablewidget shows the right height for the row – wump Apr 09 '12 at 16:04
-
I did it this way and found out that if there is too many lines so height of row is over 5000, scrolling through table (especially over that row/s) will be very slow. Do you have solution for that? Also I tried QTextEdit, scrolling over rows now works smootly enough but \n does not work in it. why? – Aleksandar Jun 27 '13 at 10:17
-
You might read http://stackoverflow.com/questions/2173151/how-to-end-line-with-qtextedit to figure out how to set line breaks. – user2672165 Dec 18 '14 at 19:20
3
just make vertical headers to fit the contents then use a text as long as you want.
QTableWidget::verticalHeader()->resizeSections(QHeaderView::ResizeToContents);

Roozbeh
- 462
- 3
- 14