用户自定义槽函数
用户自定义槽函数
一. 自定义槽函数
-
只有QObject的子类才能自定义槽
-
定义槽的类必须在声明的最开始处使用Q_OBJECT
-
类中声明槽时需要使用slots关键字
-
槽与所处理的信号在函数签名上必须移植
-
SIGNAL和SLOT所指定的名称中:
可以包含参数类型,不能包含具体的参数名
二. 计算器页面的按钮点击后可以打印按钮上的字符串
-
头文件
#ifndef _QCALCULATORUI_H_ #define _QCALCULATORUI_H_ #include <QWidget> #include <QLineEdit> #include <QPushButton> class QCalculatorUI : public QWidget { //定义槽的类必须再生命的最开始处使用Q_OBJECT Q_OBJECT private: QLineEdit* m_edit; QPushButton* m_buttons[20]; QCalculatorUI(); bool construct(); private slots: void onButtonClicked(); public: static QCalculatorUI* NewInstance(); void show(); ~QCalculatorUI(); }; #endif
-
源文件
#include "CalculatorUI.h" #include "ui_CalculatorUI.h" #include <QDebug> QCalculatorUI::QCalculatorUI() : QWidget(NULL, Qt::WindowCloseButtonHint) { } bool QCalculatorUI::construct() { bool ret = true; const char* btnText[20] = { "7", "8", "9", "+", "(", "4", "5", "6", "-", ")", "1", "2", "3", "*", "<-", "0", ".", "=", "/", "C", }; m_edit = new QLineEdit(this); if( m_edit != NULL ) { m_edit->move(10, 10); m_edit->resize(240, 30); m_edit->setReadOnly(true); } else { ret = false; } for(int i=0; (i<4) && ret; i++) { for(int j=0; (j<5) && ret; j++) { m_buttons[i*5 + j] = new QPushButton(this); if( m_buttons[i*5 + j] != NULL ) { m_buttons[i*5 + j]->resize(40, 40); m_buttons[i*5 + j]->move(10 + (10 + 40)*j, 50 + (10 + 40)*i); m_buttons[i*5 + j]->setText(btnText[i*5 + j]); //调用connect函数,将按钮的点击消息映射到某个消息处理函数 //注意:只有QObject的子类才能定义槽 //当前的点击映射到当前类对象的消息定义函数 connect(m_buttons[i*5 + j], SIGNAL(clicked()), this, SLOT(onButtonClicked())); } else { ret = false; } } } return ret; } QCalculatorUI* QCalculatorUI::NewInstance() { QCalculatorUI* ret = new QCalculatorUI(); if( (ret == NULL) || !ret->construct() ) { delete ret; ret = NULL; } return ret; } void QCalculatorUI::show() { QWidget::show(); setFixedSize(width(), height()); } //定义消息处理函数 void QCalculatorUI::onButtonClicked() { //调用sender() 是QObject的成员函数,返回一个指针,指向信号的发送者 QPushButton* btn = (QPushButton*)sender(); qDebug() << "onButtonClicked()"; qDebug() << btn->text(); } QCalculatorUI::~QCalculatorUI() { }
#include "CalculatorUI.h" #include <QApplication> int main(int argc, char *argv[]) { QApplication a(argc, argv); QCalculatorUI* cal = QCalculatorUI::NewInstance(); int ret = -1; if( cal != NULL ) { cal->show(); ret = a.exec(); delete cal; } return ret; }
-
效果