简体   繁体   English

在C ++,Qt5中创建自定义插槽

[英]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. 在python中,我们通过传递生成信号时要调用的函数来非常轻松地编写自定义插槽。 While in C++ connect function requires us to pass the address of the slot function or so i figured. 而在C ++中,connect函数需要我们传递插槽函数的地址,或者我想这样。 How do i do that. 我怎么做。 I tried using this but did'nt work. 我尝试使用它,但没有用。

Python code:: Python代码::

 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:: C ++代码::

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. 为了使用信号和插槽,您需要在类中使用Q_OBJECT宏,并标识哪些功能应该是信号和插槽。 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. 此后,您需要设置项目文件,以便MOC可以生成必要的代码。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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