Mapping signal via signalMapper

From Qt Wiki
Jump to navigation Jump to search

Template:ArticleMetaData

Introduction[edit | edit source]

Template:Abstract

Preconditions[edit | edit source]

  • Download and install the Qt SDK

Source Code[edit | edit source]

Main.cpp[edit | edit source]

  1. include <QtGui/QApplication>
  2. include "buttonwidget.h"

int main(int argc, char *argv[]) {

   QApplication a(argc, argv);
   QStringList fonts;
    fonts << "Nokia" << "QT for S60" << "Python" << "J2ME";
   ButtonWidget w(fonts);
   w.show();
   return a.exec();

}

ButtonWidget.h[edit | edit source]

  1. ifndef BUTTONWIDGET_H
  2. define BUTTONWIDGET_H
  1. include <QtGui/QWidget>
  2. include<QSignalMapper>
  3. include<QPushButton>
  4. include<QGridLayout>
  5. include<QStringList>

class ButtonWidget : public QWidget {

   Q_OBJECT

public:

   ButtonWidget(QStringList texts,QWidget *parent = 0);

signals:

   void clicked(const QString &text);

private:

   QSignalMapper *signalMapper;

};

  1. endif // BUTTONWIDGET_H

ButtonWidget.cpp[edit | edit source]

  1. include "buttonwidget.h"

ButtonWidget::ButtonWidget(QStringList texts,QWidget *parent)

   : QWidget(parent)

{

   signalMapper = new QSignalMapper();
   QGridLayout *gridLayout = new QGridLayout;
   for (int i = 0; i < texts.size(); ++i) {
       QPushButton *button = new QPushButton(texts[i]);
       connect(button, SIGNAL(clicked()), signalMapper, SLOT(map()));
       signalMapper->setMapping(button, texts[i]);
       gridLayout->addWidget(button, i / 3, i % 3);
   }
   connect(signalMapper, SIGNAL(mapped(const QString &)),
           this, SIGNAL(clicked(const QString &)));
   setLayout(gridLayout);

}

ButtonWidget::~ButtonWidget() {

   if(signalMapper)
       delete signalMapper;

}

Explanation[edit | edit source]

A list of texts is passed to the constructor. A signal mapper is constructed and for each text in the list a QPushButton is created. We connect each button's clicked() signal to the signal mapper's map() slot, and create a mapping in the signal mapper from each button to the button's text. Finally we connect the signal mapper's mapped() signal to the custom widget's clicked() signal. When the user clicks a button, the custom widget will emit a single clicked() signal whose argument is the text of the button the user clicked.

ScreenShot[edit | edit source]

File:Signalmapping.JPG

Related Links[edit | edit source]

Mapping of StandardItemModel via DataWidgetMapper in Qt