1
votes

I would like to set a subclass of QTableWidget read-only from its constructor but I cannot find a way to put the flag on all the items, and the code shown does not work since the columnCount and rowCount are called in the constructor, and therefore returning 0.

for (int i=0;i<this->columnCount();i++) {
    for (int j=0;j<this->rowCount();j++) {
        this->item(i,j)->setFlags(Qt::ItemFlag::NoItemFlags);
    }
}

Since the headers were initialized through Qt Designer with the double click form, I do not have a way to know the column/row count from code (except by hard coding it, but I would like to avoid that), and I could not find any method to apply the flags to all items.

I also have seen a few workarounds working on the modification event itself to prevent data modification, but I would also prefer avoiding that.

Is there a way to set those flags correctly or do I have to get rid of the Qt Designer part to add all the header initialization in the constructor?

2
Does your table have fixed number of rows and columns? - mike.dld
Yes, once initialized, the size will not be changing at all - Dijdkay
Can't you change item flags in Qt Designer as well then? - mike.dld
The only place I found to do so in the Designer is to click each cell in the editing form and set it as read only, I guess that a workaround I wanted to avoid would still be better than doing this - Dijdkay

2 Answers

7
votes

Hey This solves your problem...

for (int i=0;i< ui->tableWidget->rowCount();i++) {
        for (int j=0;j< ui->tableWidget->columnCount();j++) {
            QTableWidgetItem *item =  ui->tableWidget->item(i,j);
            item->setFlags(Qt::NoItemFlags);
        }
    }

Just try this, you can easily figure out the issue with your code... rowCount() and coloumnCount() api should be aligned properly and its item() API , not itemAT().. Please Check.

0
votes

Since your QTableView is being populated in auto-generated setupUi() (first widget is created, then items are added), you could add a method like setReadOnly(bool) to your subclass (which I suppose the widget in Designer is promoted to) and call it explicitly after setupUi(). Will even be more flexible since then you'd be able to use this subclass with non-read-only tables as well.