1

I want to have a read only text in QTableWidget, so I decided to insert a QLabel in each cell. Unfortunately I'm getting the following look:

enter image description here

Here is the code that I use for this:

for (int row = 1; row < ui->currentSetting1TableWidget->rowCount(); row++)
    for (int col = 1; col < ui->currentSetting1TableWidget->colorCount(); col++) {
        QLabel *label = new QLabel(ui->currentSetting1TableWidget);
        label->setText("mytext");
        ui->currentSetting1TableWidget->setCellWidget(row, col, label);
    }

I see two issues:

  1. When I run the code I got a bunch of the following warnings: QPaintDevice::metrics: Device has no metric information

  2. mytext is displayed in the corner header cell. Why is this happening? What am I doing wrong and how to fix this?

flashburn
  • 4,180
  • 7
  • 54
  • 109
  • 1
    Check the accepted answer of the following question: http://stackoverflow.com/questions/2574115/how-to-make-a-column-in-qtablewidget-read-only I think it may help you – Mo Abdul-Hameed Oct 05 '16 at 23:58
  • If you think of using a `QLabel` in any of the views, you're doing it wrong. The view already supports displaying text and images just like `QLabel` does. Item attributes set the behavior of each data item. – Kuba hasn't forgotten Monica Oct 06 '16 at 01:21

1 Answers1

4

ui->currentSetting1TableWidget->colorCount() you have code-completion-assisted typo. You wanted columnCount(). Because you specify incorrect placement for additional (colorCount() must be higher than columnCount()) labels they're assigned to coordinates (0,0) or something very close.

You're also iterating from row = 1, but rows are indexed from 0, that's why you don't have labels in the first row. It makes sense to skip first column and iterate them from 1, because of the checkboxes.

krzaq
  • 16,240
  • 4
  • 46
  • 61
  • 1
    @flashburn there's also no need for a label because you can set the column to non editable with QFlags / use QTableWidgetItem – deW1 Oct 05 '16 at 22:35
  • @deW1 Can you expand on "use QTableWidgetItem"? What do you mean by it? – flashburn Oct 05 '16 at 22:48
  • 2
    @flashburn https://gist.github.com/deW1/2ebfadaefc7c5682b2896e6d8b540417 for example – deW1 Oct 05 '16 at 22:56
  • That's a nice use of xor – krzaq Oct 05 '16 at 22:57
  • yup and by wrapping an if around it you could set conditions for table fields that you want to keep editable by not changing the flags – deW1 Oct 05 '16 at 23:02
  • OMG, I just made the same exact typo! This is ridiculous :D I got this weird message out of nowhere and googled "QPaintDevice::metrics: Device has no metric information" and the first link was this question, and it turned out I too wrote `colorCount()` instead of `columnCount()`. Thank you so much and I wish to everyone who reads this that all mysterious bugs would be solved this easily! :D – Glinka May 15 '21 at 20:43