QTableWidget cell widget "parent" questions
-
Hello all,
I have a QTableWidget that has a number of columns that need number only input and others that have text input.
Right now I just allocate a QTableWidgetItem for each cell, set the QT::ItemIsEditable flag (among others), and then do a setItem() for the cell. Basically:
for (int row = 0; row < NUM_ROWS; row++) { for (int col = 0; col < NUM_COLS; col++) { QTableWidgetItem* const i = new QTableWidgetItem; i->setFlags(Qt::ItemIsEnabled | Qt::ItemIsEditable); table->setItem(row, col, i); } }
I then just do this to get the cell text:
QString s = table->item(row, col)->text();
Some of the cells need the input data to be numbers. I figured out I can allocate a QLineEdit for those cells and then set a validator:
for (int row = 0; row < NUM_ROWS; row++) { for (int col = 0; col < NUM_COLS; col++) { QTableWidgetItem* const i = new QTableWidgetItem; if (col == 0) { QLineEdit* edit = new QLineEdit; // should this have a parent? what is it? edit->setFrame(false); edit->setValidator(new QIntValidator); // should this have a parent? what is it? t->setCellWidget(row, col, edit); } else { i->setFlags(Qt::ItemIsEnabled | Qt::ItemIsEditable); } table->setItem(row, col, i); } }
I'm just not sure if the QLineEdit and QIntValidator should have a parent and if so what that parent should be.
Also, do the cells that contain a QLineEdit widget need the QTableWidgetItem allocated and set in the table?
Thanks
-
Hi,
Rather than add widgets to every cell, you should implement a custom QStyledItemDelegate that will provide the adequate editor.
-
@bigguiness
setCellWidget()
will mean the table takes ownership of theQLineEdit
, andsetValidator()
means the line edit owns theQIntValidator
. So your parentage calls don't matter.You might prefer to use a dedicated
QSpinBox
over aQLineEdit
with a validator, have a look at it.Having said this,
setCellWidget()
is "frowned upon", because you can use too many resources if you have many items in your table. @SGaist's recommendation is the better way to do this. -
Thanks for the information about the ownership.
I'm still learning how Qt works. The custom QStyledItemDelegate is probably the best way to go but I really don't understand it and how the model/view stuff work.
Most of the comments I see just say "read the docs". Unfortunately that only helps if you have some idea of how it works already...
I'll keep trying to get it to work the way I am doing it for right now.
-
If you haven't read it yet, I suggest you read the model view tutorial which helped me understand how the various classes work together much better than by just reading the individual class documentation pages.