Create a custom slot in C++, Qt5
10,113
In order to use signals and slots, you need to have the Q_OBJECT macro in your class as well as identifying which functions should be the signals and the slots. Have a look at the documentation for a more in-depth explanation.
After this, you need to set up the project file so that MOC can generate the necessary code.
Your class definition should look like this:
class imviu: public QWidget
{
Q_OBJECT
public:
imviu(QWidget *parent=0);
public slots:
void openimg();
private:
QPushButton *btn;
};
Author by
Nitesh Agarwal
Updated on June 04, 2022Comments
-
Nitesh Agarwal almost 2 years
in python we write custom slots quite easily by passing in the function to be called when a signal is generated. While in C++ connect function requires us to pass the address of the slot function or so i figured. How do i do that. I tried using this but did'nt work.
Python code::
class imviu(QtGui.QWidget): def __init__(self): super(imvui,self).__init__() self.btn=QtGui.QPushButton('Browse') btn.clicked.connect(self.openimg) def openimg(self): #do something
C++ code::
class imviu: public QWidget { public: imviu(QWidget *parent=0); QPushButton *btn=new QPushButton("Browse"); void openimg(void); }; imviu::imviu(QWidget *parent) :QWidget(parent) { connect(btn, SIGNAL(clicked()),this,SLOT(openimg()));//this does'nt work:QObject::connect: No such slot QWidget::openimg() } void imviu::openimg() { //do something }