Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

QSignalMapper and original Sender()

Tags:

c++

qt

qt4

I have a bunch of QComboBoxes in a table. So that I know which one was triggered I remap the signal to encode the table cell location (as described in Selecting QComboBox in QTableWidget)

(Why Qt doesn't just send the cell activated signal first so you can use the same current row/column mechanism as any other cell edit I don't know.)

But this removes all knowledge of the original sender widget. Calling QComboBox* combo = (QComboBox* )sender() in the slot fails, presumably because sender() is now the QSignalMapper.

I can use the encoded row/column to lookup the QComboBox in the table widget but that seems wrong. Is there a more correct way to do it?

e.g.:

// in table creator
_signalMapper = new QSignalMapper(this);

 // for each cell
    QComboBox* combo = new QComboBox();
    connect(combo, SIGNAL(currentIndexChanged(int)), _signalMapper, SLOT(map()));
    _signalMapper->setMapping(combo, row);

   // and finally       
   connect(_signalMapper, SIGNAL(mapped(int)),this, SLOT(changedType(int)));

 // slot
 void myDlg::changedType(int row)
 {      
        QComboBox* combo = (QComboBox* )sender(); // this doesn't work !!
 }

EDIT: Added for future search: there is a new book "Advanced Qt Programming" by Mark Summerfield that explains how to do this sort of thing.

like image 416
Martin Beckett Avatar asked Feb 28 '23 22:02

Martin Beckett


1 Answers

Why not connect the QComboBox's signal straight to your slot?

QComboBox *combo = ...
connect(combo, SIGNAL(currentIndexChanged(int)), this, SLOT(changedType(int)));

And then in your slot you can use the sender() method to retrieve the QComboBox that was changed.

void myDlg::changedType(int row)
{
    QComboBox *combo = qobject_cast<QComboBox *> sender();

    if(combo != 0){
        // rest of code
    }
}

Alternatively, to use the QSignalMapper method you would just need to change your slot to use the mapping you set up:

void myDlg::changedType(int row)
{
    QComboBox *combo = qobject_cast<QComboBox *>(_signalMapper->mapping(row));

    if(combo != 0){
        // rest of code
    }
}        
like image 57
Kyle Lutz Avatar answered Mar 06 '23 19:03

Kyle Lutz