Search code examples
c++qtsignals-slotsqcustomplot

connecting a basic signal mousepress


I am using QCustomPlot where I am trying to write a code that will rescale my axes once the user press the mouse and drags. I did:

   connect(ui->plot, SIGNAL(mousePress(QMouseEvent *event)), this,  SLOT(mousedrag(QMouseEvent*))); 

and I keep getting:

QObject::connect: No such signal QCustomPlot::mousePress(QMouseEvent *event)

But mouseWheel(QWheelEvent*) and both mouseWheel and mousePress have signals declared in the QCustomPlot library.

Where am I going wrong? Also if someone has a better signal to trigger my function mousedrag(QMouseEvent*) which rescales the the y2 axis according to y1 axis I am open for suggestions.


Solution

  • The signal signature passed to connect is invalid. The parameter names are not a part of the signature. You should also remove any whitespace so that connect doesn't have to normalize the signatures. A normalized signature has no unnecessary whitespace and outermost const and reference must be removed, e.g. SIGNAL(textChanged(QString)), not SIGNAL(textChanged(const QString &)).

                                                     remove
                                                     vvvvv
    connect(ui->plot, SIGNAL(mousePress(QMouseEvent *event)), this,             
            SLOT(mousedrag(QMouseEvent*)));
    

    Do the below instead:

    // Qt 5
    connect(ui->plot, &QCustomPlot::mousePress, this, &MyClass::mousedrag);
    // Qt 4
    connect(ui->plot, SIGNAL(mousePress(QMouseEvent*)), SLOT(mousedrag(QMouseEvent*));
    

    Sidebar

    TL;DR: This sort of API design is essentially a bug.

    Events and signal/slot mechanism are different paradigms that the QCustomPlot's design mangles together. The slots connected to these signals can be used in very specific and limited ways only. You have to use them exactly as if they were overloads in a derived class. This means:

    1. Each signal must have either 0 or 1 slots connected to it.

    2. The connections must be direct or automatic to an object in the same thread.

      You cannot use queued connections: by the time the control returns to the event loop, the event has been destroyed and the slot/functor will be using a dangling pointer.