PDA

View Full Version : connect signal to a new QtableWidget



hass26
7th March 2015, 20:06
I would like to connect a signal to new tables everytime the user clicks on any of their cells.

The user creates the QWidgetTables as needed (with: table = new QTableWidget(this) ) and adds them to an existing QTabWidget

I cannot figure out a way to issue the signal from the unknown QWidgetTable.

how do i find "table" in the line below and where should I make the connection?

connect(table,SIGNAL(itemClicked(QTableWidgetItem) ),this,SLOT(doSomething(QTableWidgetItem)));

Added after 21 minutes:

I can interact with the tables if I write the connection just after I create the tables in the same function. That is to say something like



void myclass::createTables(void)
{
table = new QTableWidget(this);
...
..
myTabWidget->addTab(table,"name");
...
connect(table,SIGNAL(itemClicked(QTableWidgetItem) ),this,SLOT(doSomething(QTableWidgetItem)));
}


However, I can interact with only the last table but not the earlier tables. How do I overcome this?

Thanks

ChrisW67
7th March 2015, 20:10
Why do you need to find anything? You create the table then you connect it. Assuming "this" is the tab widget...


QTableWidget *table = new QTableWidget(this);
connect(table,SIGNAL(itemClicked(QTableWidgetItem) ),this,SLOT(doSomething(QTableWidgetItem)));

hass26
7th March 2015, 20:26
Yes I can do that, but I need to re-write the code as the table is accessible from many other functions.
But I think that is the safest way. Thanks

ChrisW67
8th March 2015, 09:47
Assuming the variable "table" is a member variable then you are discarding the pointer value every time you create a new table widget. Since you only have on pointer you can only use it to access one table.

If you are sharing slot with all the table widget connected to it then you can use the sender() function in the slot to work out which activated the slot. Something like


void Class::slot(...)
{
QTableWidget *sender = qobject_cast<QTableWidget *>(sender);
if (sender) {
// do stuff
}
}

There may be a better design... but we do not know enough about what you are doing.

anda_skoa
8th March 2015, 09:59
If you need access to the n-th table you create at any time after creation, put the tables into a numerically indexed container.

For the connect() that would only make sense if you disconnect and reconnect later on, otherwise connect after creation is way cleaner.

Cheers,
_

hass26
14th March 2015, 20:26
Eventually that is what I did. It is cleaner and works.