首页 文章

信号和插槽的工作

提问于
浏览
1

我对信号和插槽的实际工作方式有一个基本的疑问 . 这是我的代码段 .

finddialog.cpp:

#include "finddialog.h"
#include <QtGui>
#include <QHBoxLayout>
#include <QVBoxLayout>


FindDialog::FindDialog(QWidget *parent) :   QDialog(parent) {

    //VAR INITIALIZATIONS
    label = new QLabel(tr("Find &what:"));
    lineEdit = new QLineEdit;
    label->setBuddy(lineEdit);

    caseCheckBox = new QCheckBox(tr("Match &case"));
    backwardCheckBox = new QCheckBox(tr("Search &backward"));

    findButton = new QPushButton("&Find");
    findButton->setDefault(true);
    findButton->setEnabled(false);

    closeButton = new QPushButton(tr("&Quit"));

    //SIGNALS & SLOTS
    connect (lineEdit, SIGNAL(textChanged(const QString&)),this, SLOT(enableFindButton(const QString&)));
    connect (findButton, SIGNAL(clicked()), this, SLOT(findClicked()));
    connect (closeButton,SIGNAL(clicked()), this, SLOT(close()));

   //Layout
    QHBoxLayout *topLeftLayout = new QHBoxLayout;
    topLeftLayout->addWidget(label);
    topLeftLayout->addWidget(lineEdit);

    QVBoxLayout *leftLayout = new QVBoxLayout;
    leftLayout->addLayout(topLeftLayout);
    leftLayout->addWidget(caseCheckBox);
    leftLayout->addWidget(backwardCheckBox);

    QVBoxLayout *rightLayout = new QVBoxLayout;
    rightLayout->addWidget(findButton);
    rightLayout->addWidget(closeButton);
    rightLayout->addStretch();

    QHBoxLayout *mainLayout = new QHBoxLayout;
    mainLayout->addLayout(leftLayout);
    mainLayout->addLayout(rightLayout);

    //Complete window settings

    setLayout(mainLayout);

    setWindowTitle(tr("Find"));
    setFixedHeight(sizeHint().height());

}

//Function Definition
void FindDialog::findClicked()  {

    QString text = lineEdit->text();
    Qt::CaseSensitivity cs = caseCheckBox->isChecked() ? Qt::CaseSensitive : Qt::CaseInsensitive;
    if(backwardCheckBox->isChecked())
        emit findPrevious(text, cs);
    else
        emit findNext(text,cs);
}

void FindDialog::enableFindButton(const QString &text1) {
    findButton->setEnabled(!text1.isEmpty());
}

使用此代码,编译器如何知道传递给enableFindButton(QString&)函数的内容 . 没有函数调用enableFindButton() . 在connect语句中有一个对enableFindButton()的引用,但它不是更像原型,因为我们没有提供在其参数中使用的变量的名称?

connect (lineEdit, SIGNAL(textChanged(const QString&)),this, SLOT(enableFindButton(const QString&)));

这里只有(const QString&)是参数,并且没有给出变量 . 如果没有明确地传递它,应用程序如何知道它的参数是什么?

void FindDialog::enableFindButton(const QString &text1) {
    findButton->setEnabled(!text1.isEmpty());
}

这里也&text1是一个参考参数 . 但到了什么?在输入所有内容后我现在什么都不懂! : - |

2 回答

  • 0

    Qt正在生成使您在构建项目时工作的代码 .

    SIGNALSLOTpreprocessor macrosqobjectdefs.h中定义preprocessor macros

    然后在构建项目时在QT中通过 moc 拾取这些内容,并生成所需的所有代码,然后进行编译 .

    可以找到一个可以更详细地解释这个问题的体面页面here

  • 1

    C源代码由Qt元对象编译器(moc)处理 . 它为QObject插槽生成“签名”字符串 . 签名包含方法名称和参数(类型,参数的名称在签名中无关紧要) . 每当发出信号时,直接执行签名匹配(在直接连接的情况下)或在事件循环中(对于排队的连接),并且调用相应的方法 . Moc编译器生成所有必要的代码,这些代码将匹配签名并调用方法 . 如果有兴趣,请查看其中一个生成的* .cxx文件 .

相关问题