1

I am new to Qt and trying to write signal and slot. Below is the code I was trying to run. with SLOT and SIGNAL keywords on "connect" function, it works fine. But I do not want to use SIGNAL and SLOT keywords on connect function, instead want to use a different approach.

  class MyWindow:public QMainWindow
  {
      Q_OBJECT
  public:
      MyWindow();
  };

  MyWindow::MyWindow()
  {
     QWidget *widget=new QWidget;
     QHBoxLayout *layout =new QHBoxLayout;
     QSpinBox *mySlide = new QSpinBox;
     mySlide->setRange(0,10);
     QLCDNumber *lcdNumber= new QLCDNumber;
     layout->addWidget(mySlide);
     layout->addWidget(lcdNumber);

       connect(mySlide,SIGNAL(valueChanged(int)),lcdNumber,SLOT(display(int)));
    // connect(mySlide, &QSpinBox::valueChanged,lcdNumber, &QLCDNumber::display);

      widget->setLayout(layout);
      setCentralWidget(widget);
   }

In above code, uncommented connect function works fine but commented connect function does not work. I am getting error "no matching function to call MyWindow::connect". Not sure what mistake I made here. I was following this article from qt.

http://doc.qt.io/qt-5/qtopengl-hellogl2-window-cpp.html

LilRazi
  • 422
  • 5
  • 20

1 Answers1

2

The problem is that both the signal -- QSpinBox::valueChanged -- and the slot -- QLCDNumber::display -- have multiple overloads for different argument types. You have a few options.

1) Use a static_cast to disambiguate between the various signal and slot overloads...

connect(mySlide,
        static_cast<void(QSpinBox::*)(int)>(&QSpinBox::valueChanged),
        lcdNumber,
        static_cast<void(QLCDNumber::*)(int)>(&QLCDNumber::display));

or...

2) Just use a lambda...

connect(mySlide, static_cast<void(QSpinBox::*)(int)>(&QSpinBox::valueChanged),
        [lcdNumber](int value)
        {
          lcdNumber->display(value);
        });

Although using the lambda still requires a static_cast on the signal.

G.M.
  • 9,830
  • 2
  • 10
  • 17
  • Thank you so much. It did work. But just curious to know why connect(mySlide, SIGNAL(valueChanged(int)),lcdNumber, &QLCDNumber::display) did not work. the first part is explicitly signal. – LilRazi Jun 24 '17 at 17:24
  • You can't mix and match between the various signal/slot syntaxes. It's either all SIGNAL and SLOT syntax *or* the new pointer to member syntax. – G.M. Jun 24 '17 at 17:30