《Qt5学习笔记6》信号和槽的多种组合

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的信号和槽机制,能够实现很复杂的功能。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值