问题
I need to connect a button to a member function from another class. Here the class' code :
int g_switch_value = 0;
int filterInt = 0;
int lastfilterInt = -1;
void MoyenEtMedian::switch_callback(int position, void* object)
{ MoyenEtMedian* moyetmed = (MoyenEtMedian*) object;
filterInt = position;
}
void MoyenEtMedian::exec(void)
{
const char* name = "Filtres";
IplImage* img = cvLoadImage( "image.png" );
IplImage* out = cvCreateImage( cvGetSize(img), IPL_DEPTH_8U, 3 );
cvNamedWindow( name, 1 );
cvShowImage(name, out);
// Create trackbar
cvCreateTrackbar2( "Filtre", name, &g_switch_value, 1, &MoyenEtMedian::switch_callback, this );
while( 1 ) {
switch( filterInt ){
case 0:
cvSmooth( img, out, CV_BLUR, 7, 7 );
break;
case 1:
cvSmooth( img, out, CV_MEDIAN, 7, 7 );
break;
}
if(filterInt != lastfilterInt){
cvShowImage(name, out);
lastfilterInt = filterInt;
}
if( cvWaitKey( 15 ) == 27 )
break;
}
cvReleaseImage( &img );
cvReleaseImage( &out );
cvDestroyWindow( name );
}
Here's the .cpp of the GUI (created with Qt Designer):
FenPrincipale::FenPrincipale(QWidget *parent) :
QWidget(parent),
ui(new Ui::FenPrincipale)
{
ui->setupUi(this);
QObject::connect(ui->bMoyMed,SIGNAL(clicked()),MoyenEtMedian,SLOT(MoyenEtMedian::exec()));
}
I'm getting the "not declard in this scope" error for MoyenEtMedian, even when passing it directly.
UPDATE : #include was missing. The "not declared in this scope" issue is resolved.
But I have another one :
"expected primary-expression before ',' token" concerning :
QObject::connect(ui->bMoyMed,SIGNAL(clicked()),MoyenEtMedian,SLOT(exec()));
I have declared the SLOT in the moyenetmedian.h file :
#ifndef MOYENETMEDIAN_H
#define MOYENETMEDIAN_H
#include "ui_fenprincipale.h"
class MoyenEtMedian
{Q_OBJECT
public:
MoyenEtMedian();
static void switch_callback(int position, void*);
public slots :
void exec(void);
};
#endif // MOYENETMEDIAN_H
回答1:
Until Qt 5.0, the destination of a connection has to be declared as a SLOT in the class declaration.
Qt 5.0 introduced some new syntax for connection. One of them allows you to connect a signal to any member function: http://qt-project.org/doc/qt-5.0/qtcore/qobject.html#connect-4
回答2:
You need to create an object MoyenEtMedian
here a sample with FenPrincipale
member (or you can pass your object as argument to the FenPrincipale
contructor if it was already created).
FenPrincipale::FenPrincipale(QWidget *parent) :
QWidget(parent),
ui(new Ui::FenPrincipale)
{
ui->setupUi(this);
moyenEtMedian = new MoyenEtMedian();
QObject::connect(ui->bMoyMed,SIGNAL(clicked()), moyenEtMedian, SLOT(exec()));
}
In your code MoyenEtMedian
is a class not an object.
来源:https://stackoverflow.com/questions/13805271/member-function-as-a-qt-slot