Use of setCellWidget (in QTableWidget) and signal connections

The widgets set on the cells have nothing to do with the contents of the table, so you won’t get signals from the table in such a case. If you have a row or column of widgets potentially emitting signals, and you want one slot to be notified of the row/column index of the widget that was triggered, then QSignalMapper [qt.nokia.com] could be the way to go.

The following example illustrates how this can be done:

main.cpp
============================================

  1. #include <QtGui>
  2.  
  3. class CustomWidget : public QWidget{
  4.     Q_OBJECT
  5.  
  6. public:
  7.     CustomWidget(QWidget *parent = 0 , Qt::WindowFlags f = 0){
  8.         table = new QTableWidget(7,4,this);
  9.         signalMapper = new QSignalMapper(this);
  10.         statusBar = new QStatusBar(this);
  11.  
  12.         for (int i = 0; i< table->rowCount(); i++){
  13.             QComboBox *cb = new QComboBox();
  14.             cb->addItems((QStringList() << "Item 1" << "Item 2" << "Item 3"));
  15.             table->setCellWidget(i,2,cb);
  16.             connect(cb, SIGNAL(currentIndexChanged(int)), signalMapper, SLOT(map()));
  17.             signalMapper->setMapping(cb, i);
  18.         }
  19.         connect(signalMapper, SIGNAL(mapped(int)), this, SLOT(demoSlot(int)));
  20.         setLayout(new QVBoxLayout);
  21.         layout()->addWidget(table);
  22.         layout()->addWidget(statusBar);
  23.         resize(400,300);
  24.         show();
  25.     }
  26.  
  27.  
  28. public slots:
  29.     void demoSlot(int row){
  30.         QComboBox *cb = static_cast<QComboBox *>(table->cellWidget(row,2));
  31.         statusBar->showMessage(QString("Combobox changed at row %1, "\
  32.                                        "new value: %2").arg(row+1).arg(cb->currentText()), 5000);
  33.     }
  34.  
  35. private:
  36.     QTableWidget *table;
  37.     QSignalMapper *signalMapper;
  38.     QStatusBar *statusBar;
  39. };
  40.  
  41. #include "main.moc"
  42.  
  43. int main( int argc, char** argv ){
  44.  
  45.    QApplication app( argc, argv );
  46.         CustomWidget w;
  47.         w.show();
  48.    return app.exec();
  49. }

============================================

No comments

Write a comment

Sorry, you must be logged in to post a comment.