《Qt5学习笔记6》信号和槽的多种组合
2016-03-09 21:33
393 查看
Qt中的信号和槽机制非常灵活,并且允许像如下使用信号和槽机制:
1、一个信号可以和(一个或多个)信号连接
2、一个信号可以和(一个或多个)一个槽连接
3、(一个或多个)信号可以和一个槽连接
下面看个简单的程序:
注释已经写得很清楚了。灵活地使用Qt的信号和槽机制,能够实现很复杂的功能。
1、一个信号可以和(一个或多个)信号连接
QObject::connect(lineEdit1, SIGNAL(textChanged(QString)), lineEdit2, SIGNAL(textChanged(QString)));
2、一个信号可以和(一个或多个)一个槽连接
QObject::connect(lineEdit1, SIGNAL(textChanged(QString)), lineEdit2, SLOT(setText(QString))); QObject::connect(lineEdit1, SIGNAL(textChanged(QString)), lineEdit3, SLOT(setText(QString)));
3、(一个或多个)信号可以和一个槽连接
下面看个简单的程序:
#include <QApplication>运行效果:
#include <QDialog>
#include <QLineEdit>
#include <QLabel>
#include <QHBoxLayout>
#include <QVBoxLayout>
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
QDialog *dialog = new QDialog;
dialog->setWindowTitle("Test for Signals&Slots of QT");
QLineEdit *lineEdit1 = new QLineEdit;
QLineEdit *lineEdit2 = new QLineEdit;
QLineEdit *lineEdit3 = new QLineEdit;
QLabel *label1 = new QLabel("LineEdit1:");
QLabel *label2 = new QLabel("LineEdit2:");
QLabel *label3 = new QLabel("LineEdit3:");
label1->setBuddy(lineEdit1);
label2->setBuddy(lineEdit2);
label3->setBuddy(lineEdit3);
//改变lineEdit1会改变lineEdit2和lineEdit3
QObject::connect(lineEdit1, SIGNAL(textChanged(QString)), lineEdit2, SLOT(setText(QString))); QObject::connect(lineEdit1, SIGNAL(textChanged(QString)), lineEdit3, SLOT(setText(QString)));
//改变lineEdit2会改变lineEdit1和lineEdit3,但是2和3并没有直接连接,而是通过1间接连接
QObject::connect(lineEdit2, SIGNAL(textChanged(QString)), lineEdit1, SLOT(setText(QString)));
QHBoxLayout *topLayout = new QHBoxLayout;
topLayout->addWidget(label1);
topLayout->addWidget(lineEdit1);
QHBoxLayout *middleLayout = new QHBoxLayout;
middleLayout->addWidget(label2);
middleLayout->addWidget(lineEdit2);
QHBoxLayout *bottomLayout = new QHBoxLayout;
bottomLayout->addWidget(label3);
bottomLayout->addWidget(lineEdit3);
QVBoxLayout *mainLayout = new QVBoxLayout;
mainLayout->addLayout(topLayout);
mainLayout->addLayout(middleLayout);
mainLayout->addLayout(bottomLayout);
dialog->setLayout(mainLayout);
dialog->show();
return app.exec();
}
注释已经写得很清楚了。灵活地使用Qt的信号和槽机制,能够实现很复杂的功能。
相关文章推荐
- QVTKWidget与Qt5.5.0以后版本不兼容!
- Qt5位置相关函数
- 一起看代码来玩玩QT之24 AudioPlayer
- 一起看代码来玩玩QT之23 audioRecord
- 一起看代码来玩玩QT之22 VideoPlayer (linux 下 )
- QT模拟时钟
- Qt国际化详细介绍
- QUdpSocket收不到回复及分析
- ubuntu技巧--ubuntu Qt Creator debug
- Qt控制台输出QString
- Qt编写串口通信程序 讲解
- 在Ubuntu下安装Qt creator 5
- QT5串口通信
- Ubuntu下 嵌入式Qt开发环境的搭建--转载
- Exposing Qt's Q_ENUMS to QML
- Qt无法输入中文问题解决
- QT中各种MessageBox的使用
- qt
- 学习记录-Qt读取条码扫描枪
- QT-QMainWindow布局设置