Dijdkay Dijdkay - 3 months ago 22
C++ Question

Iterate over QTableWidget cells in constructor?

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?

Answer

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.