`
qimo601
  • 浏览: 3417236 次
  • 性别: Icon_minigender_1
  • 来自: 苏州
社区版块
存档分类
最新评论

Qt自定义槽和信号

阅读更多

 

//customwnd.h
#ifndef __CUSTOM_WINDOW_H__
#define __CUSTOM_WINDOW_H__

#include "qapplication.h"
#include "qwidget.h"
#include "messagebox"
#include "qpopumenu.h"

class CustomWnd:public QWidget
{
    Q_OBJECT  //
如果要自定义槽和消息,必须在这里调用这个宏,否则自定义的槽和消息将不会起作用
  
public:
    CustomWnd(QWidget *parent = 0, const char *name = NULL);
    ~CustomWnd();

public slots:      //
自定义槽, 如果要自定义保护槽, 就声明为 protected slots:
    void btnMessage();  //
自定义无参数槽.

    void slotTest(QString); //
自定义槽.

signals:           //
自定义信号, 如果要自定义保护信号, 就在protected: 后声明.
            //
自定义信号只需要在这里声明, 然后将槽连接到信号即可,无需实现信号函数.信号函数与槽函数的返回值类型在任何时候都可以不同; 而且如果不关心信号传递下来的参数, 信号函数与槽函数的参数列表也可以不相同, 但是如果要访问信号传递下来的任何参数时, 信号函数与槽函数的参数列表必须相同.
    void explains(); //
如果要自定义槽和信号, explains信号是必须的

    void sigTest(QString str);  //
自定义信号.

private:
    QPushButton *m_pushBtnMsg;
};
#endif

//customwnd.cpp

CustomWnd::CustomWnd(QWidget *parent = 0, const char *name = NULL)
    :QWidget(parent, name)
{
    m_pushBtnMsg = new QPushButton("MessageButton", this);
    m_pushBtnMsg->show();
    connect(m_pushBtnMsg, SIGNAL(clicked()), this, SLOT(btnMessage()));  //
将自定义槽连接到内部信号, 这里就跟消息映射函数相似.

    connect(this, SIGNAL(sigTest(QString)), this, SLOT(slotTest(QString)));  //
将自定义槽连接到自定义信号

}

CustomWnd::~CustomWnd()
{
    delete m_pushBtnMsg;
}

void CustomWnd::btnMessage()
{
    QMessageBox::warning(this, "WARNING", "just for test: will emit test signal");
    emit sigTest(QString("Test Signal"));  //
发出自定义信号
}

void CustomWnd::slotTest(QString str)
{
    QMessageBox::warning(this, "Customized signal test", str);
}

//test.cpp

#include "customwnd.h"

int main(int argc, char **argv)
{
    QApplication a(argc, argv);
    CustomWnd wnd;

    a.setMainWidget(&wnd);
    wnd.show();

    return a.exec();
}
<!--[if !supportLineBreakNewLine]-->
<!--[endif]-->

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics