Auto line-break with QLabel within QTableWidget
-
I'm working on a
QTableWidget
with someQLabel
inside it, but I need theQLabel
to line-break automatically. I've triedsetWordWrap
from this question:QVBoxLayout *newL = new QVBoxLayout; QTableWidget * tab = new QTableWidget; tab->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch); newL->addWidget(tab); tab->setRowCount(1); tab->setColumnCount(1); QLabel *lb = new QLabel; lb->setText("testing"); lb->setWordWrap(true); tab->setCellWidget(0,0,lb); QWidget *window = new QWidget; window->setLayout(newL); window->show();
Problems
- If one word is really lengthy, the wordWrap doesn't move to a new line. Instead, it just expand into outer region:
lb->setText("testtesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttestawd");
2. If there're multiple lines (more than 2), the QTableWidget doesn't create more lines, so the lower lines are not shown:lb->setText("test\ntest\ntest\ntest\ntest\ntest");
3. Even if there're only spaces between words, the QTableWidget still doesn't expand more than 2 lines:lb->setText("test test test test test test test");
Questions- For the first problem, I'd like the text to switch to new line exactly at the point that the text go to outer region, even if there're no
\n
character (same way with MS Word). - For the second and third problem, I'd like the
QWidgetTable
to provide enough space to show all the text.
Please help. Thanks in advance.
-
@silverfox said in Auto line-break with QLabel within QTableWidget:
For the first problem, I'd like the text to switch to new line exactly at the point that the text go to outer region, even if there're no \n character (same way with MS Word).
QLabel wraps at word boundaries, e.g. the transition from alphanumerics to whitespace, to fit the width available. If you want to change that behaviour then you need to subclass QLabel and implement your own QWidget::paintEvent(), sizeHint(), and possibly other things.
QTextEdit may be an alternate choice.
For the second and third problem, I'd like the QWidgetTable to provide enough space to show all the text.
The default behaviour is that the table widget, through its QHeaderViews, dictates the size of the cell and therefore the space available for the widget you put in it to use. This ignores any suggested size that the widget might provide. You can change that behaviour:
// All rows in table tab->verticalHeader()->setSectionResizeMode(QHeaderView::ResizeToContents); // one specific row tab->setSectionResizeMode(1, QHeaderView::ResizeToContents);
That said, I have no idea why you are putting a label widget into a table cell just to display text. The QTableWidget is quite capable of displaying text from its model on its own. In that case you can use a QItemDelegate to thoroughly customise the appearance of text coming from the model.