《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();
}
运行效果:

《Qt5学习笔记6》信号和槽的多种组合_第1张图片

注释已经写得很清楚了。灵活地使用Qt的信号和槽机制,能够实现很复杂的功能。

你可能感兴趣的:(qt5,信号和槽)