简体   繁体   中英

Create a custom slot in C++, Qt5

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
}

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;
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM