PDA

View Full Version : QTable of comoboxes



terhje
4th May 2012, 14:33
Hi, i have a QTableWidget of comboboxes.
I set the comboboxes like this:

QComboBox *item = new QComboBox();
ui->tableWidget->setCellWidget(i,0,item);

my problem is getting information from the combobox later. i need to get a hold of currentText()..
ui->tableWidget->cellWidget(row,kol)->(no option of currentText())
how can i get a hold of the combobox?

thx,

Zlatomir
4th May 2012, 16:09
ui->tableWidget->cellWidget(row,kol)->(no option of currentText())

I doesn't have an option because that method returns a QWidget* (http://doc-snapshot.qt-project.org/4.8/qtablewidget.html#cellWidget) (and QWidget doesn't know anything about the derived class object that it points to)
You need to cast the pointer, use dynamic_cast or qobject_cast (http://doc-snapshot.qt-project.org/4.8/qobject.html#qobject_cast) and don't forget to check for 0 (null pointer) especially if you have many kinds of widgets in the table (not only QComboBox)

terhje
4th May 2012, 17:33
Thx for quick reply! Im a bit of a newbie with this. do you have an example of casting the pointer with dynamic_cast or qobject_cast?
Thx,

Zlatomir
4th May 2012, 20:48
You have an qobject_cast example in the link i gave you, and it's similar with dynamic_cast (but it is supposed to be used with instances of classes derived from QObject)


QComboBox* comboFromTableWidget = dynamic_cast<QComboBox*>(ui->tableWidget->cellWidget(row,kol));
if(comboFromTableWidget != 0) /*test for null pointer (dynamic_cast returns null if the pointer can't be "casted" to a pointer to a derived class)*/
{
//use the combo here... because the pointer holds an address of a QComboBox...
QString text = comboFromTableWidget->currentText();
}


//i suggest you read a C++ book (the two volumes of Thinking in C++ can be found free of charge - just google it), else you will have a lot of problems - and Qt is actually "cute" and the saying that Qt actually brings to front the "much smaller and cleaner language (http://www2.research.att.com/~bs/bs_faq.html#really-say-that)" that struggle to get out from C++ is true ;), but still you need pretty good C++ knowledge to enjoy using Qt framework - especially OOP <dynamic_cast is somehow OOP related ;)>