一.Qt中的信号处理
Qt消息模型:
- Qt封装了具体操作系统的消息机制
- Qt遵循经典的GUI消息驱动事件模型
Qt中定义了与系统消息相关的概念;
Qt中的消息处理机制:
Qt的核心 QObject::cinnect函数:
Qt中的“新”关键字:
实验1 初探信号与槽
#include <QtGui/QApplication>
#include <QPushButton>
int main(int argc, char *argv[])
{QApplication a(argc, argv);//应用程序对象QPushButton b;//按钮对象b.setText("Click me to quit!");b.show();//通过connect函数 将按钮对象的点击事件信号 映射到 a对象的quit()成员函数QObject::connect(&b, SIGNAL(clicked()), &a, SLOT(quit()));return a.exec();
}
运行结果:
二.自定义槽
- 只有QObject的子类才能自定义槽
- 定义槽的类必须在声明的最开始处使用Q_OBJECT
- 类中的声明槽时需要使用slots关键字
- 槽与所处理的信号在函数签名上必须一致
- SIGNAL和SLOT所指定的名称中:可以包含参数类型,不能包含具体的参数名
实验2 为计算器界面添加消息处理函数,所有按钮对应一个槽,打印同样log
目录:
QCalculatorUI.h:
#ifndef _QCALCULATORUI_H_
#define _QCALCULATORUI_H_#include <QWidget>
#include <QLineEdit>
#include <QPushButton>class QCalculatorUI : public QWidget
{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
QCalculatorUI.cpp:
#include "QCalculatorUI.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(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()
{QPushButton* btn = (QPushButton*)sender();qDebug() << "onButtonClicked()";qDebug() << btn->text();
}QCalculatorUI::~QCalculatorUI()
{}
main.cpp:
#include <QApplication>
#include "QCalculatorUI.h"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;
}
运行结果:点击 ”7“ ”8“ ”9“