Search code examples
c++qtsignals-slots

QComboBox signal not trigged


I have checked my code several times and i still can't get why it is not working. I use a QComboBox connected to a slot in the class like this :

this->choixCam = new QComboBox;
this->choixCam->addItem("Camera 1");
this->choixCam->addItem("Camera 2");
this->choixCam->addItem("Camera 3");
this->choixCam->addItem("All cameras");
QObject::connect(this->choixCam, SIGNAL(currentIndexChanged(int)), this, SLOT(this->selectCam(int)));

This previous part of code is defined is the constructor of my class MainWindows, called in the main. The definition in the header file is the following :

public:
    QComboBox* choixCam;
public slots:
    void selectCam(int choixCam);

I tried with successfully to run the slot from another signal.

Using the signal with QString, the signal activated(int) or trying an exemple find on the net didn't work neither. Signals/slots mecanism also work for QButton and QSpinBox.

I am running out of idea. Some help would be very appreciate. Thank you.


Solution

  • @eyllanesc answer should work. Just change SLOT(this->selectCam(int)) to SLOT(selectCam(int)).

    But why isnt it the same for QT? Lets have a look at the connect method:

    QMetaObject::Connection QObject::connect(const QObject *sender, const char *signal,const QObject *receiver, const char *method,
    Qt::ConnectionType type)
    

    (https://github.com/qt/qtbase/blob/e4c39d5e1e7ee8c2bba273e6d613ec519b7fa9c2/src/corelib/kernel/qobject.cpp#L2659)

    and at the SIGNAl and SLOT definition:

    #define SLOT(a)     "1"#a
    #define SIGNAL(a)   "2"#a
    

    QT uses c-strings to identify the signals and slots for qobjects. These strings are used as keywords in some kind of dictionary over all qobjects, signals and slots. Just try std::cout << SIGNAL(some text) << std::endl; to see what SIGNAL and SLOT do.

    Thats why can call connect even without SIGNAL and SLOT:

    connect(this->choixCam, "2currentIndexChanged(int)", this, "1selectCam(int)");
    

    Now you know that SLOT(this->selectCam(int)) will produce "1this->selectCam(int)" as keyword instead of "1selectCam(int)"

    The SIGNAL and SLOT definitions are used because most IDEs disable C++ autocompletion inside quotation marks, which makes it hard to write the correct function signature.