How do I connect a signal to a slot in a static me

2019-08-17 15:16发布

问题:

I'm trying to show a popup window from within a static method:

 void MainThread::popup(void){
 static klassePopup* roiPopup;
 roiPopup = new SavingROI();
 roiPopup->show();}

This code works fine, I get my window with two QPushbuttons, but I don't understand when I should connect the SIGNAL clicked() with a SLOT.

The following code didn't work:

 connect(roiPopup->getsaveROIButton(),SIGNAL(clicked()),this,SLOT(saveROI(cv::Mat)));

I know that the question isn't clear but the code is little bit complicated to copy here

回答1:

Let's take a closer look at your connect:

connect( roiPopup->getsaveROIButton(), SIGNAL( clicked(         ) ),
         this                        , SLOT  ( saveROI( cv::Mat ) ) );

I intentionally reformatted it to show a couple of things:

  1. You are trying to connect clicked which has no parameters to your slot saveROI which expects a parameter. This does not work because the connection does not know where to get the value for cv::Mat for.
    Instead, you need to make a slot which does not retrieve parameters either.
  2. As already pointed out by ahenderson in a comment, you cannot use this from within a static method.

The main question is, why do you need a static method? Because you only want a single popup window? If that is the only reason, this is the way you would normally do it:

MainThread.h:

class klassePopup;  // Note: This is a "forward declaration". 
                    //       Google it if you don't know what that is.

class MainThread : public QObject // or anything else which inherits QObject
{
public:
    MainThread();
    ~MainThread();

public:
    void popup(); // not static

private slots:
    saveROI(); // no parameter

private:
    klassePopup* _roiPopup;
};

MainThread.cpp:

#include "klassePopup.h"
#include "SavingROI.h"

MainThread::MainThread() :
   _roiPopup( new SavingROI() )
{
    bool bConnectionSucceeded
        = connect( _roiPopup->getsaveROIButton(), SIGNAL( clicked() ),
                 ( this                         , SLOT  ( saveROI() ) );
}

MainThread::~MainThread()
{
    delete _roiPopup;
}

void MainThread::popup()
{
    _roiPopup.show();
}

void MainThread::saveROI()
{
    // retrieve your cv::mat parameter from somewhere else
}

This solution would work, but if you want to call that from a static method, you have to create your MainThread instance in that static method as well.