一、头文件finddialog.h
#ifndef FINDDIALOG_H
#define FINDDIALOG_H
#include <QDialog>
class QLabel;
class QLineEdit;
class QCheckBox;
class QPushButton;
class FindDialog : public QDialog
{
Q_OBJECT
public:
FindDialog(QWidget *parent = nullptr);
~FindDialog();
signals:
void findNext(const QString& str, Qt::CaseSensitivity cs); // 信号函数无需定义
void findPrevious(const QString& str, Qt::CaseSensitivity cs); // 信号函数无需定义
private slots:
void findClicked();
void enbaleFindButton(const QString& next);
private:
void createConnect();
private:
QLabel* label;
QLineEdit* lineEdit;
QCheckBox* caseCheckBox;
QCheckBox* backwardCheckBox;
QPushButton* findBtn;
QPushButton* closeBtn;
};
#endif // FINDDIALOG_H
二、实现文件finddialog.cpp
#include "finddialog.h"
#include <QLabel>
#include <QLineEdit>
#include <QCheckBox>
#include <QPushButton>
#include <QHBoxLayout>
#include <QDebug>
FindDialog::FindDialog(QWidget *parent)
: QDialog(parent)
{
label = new QLabel(tr("Find &what:"));
lineEdit = new QLineEdit;
label->setBuddy(lineEdit);
caseCheckBox = new QCheckBox(tr("Match &case"));
backwardCheckBox = new QCheckBox(tr("Search &backward"));
findBtn = new QPushButton(tr("&Find"));
findBtn->setDefault(true);
findBtn->setEnabled(false);
closeBtn = new QPushButton(tr("Close"));
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(findBtn);
rightLayout->addWidget(closeBtn);
rightLayout->addStretch();
QHBoxLayout* mainLayout = new QHBoxLayout(this);
mainLayout->addLayout(leftLayout);
mainLayout->addLayout(rightLayout);
createConnect();
setWindowTitle("Find");
setFixedHeight(sizeHint().height());
}
FindDialog::~FindDialog()
{
}
void FindDialog::createConnect()
{
connect(lineEdit, &QLineEdit::textChanged, this, &FindDialog::enbaleFindButton);
connect(findBtn, &QPushButton::clicked, this, &FindDialog::findClicked);
connect(closeBtn, &QPushButton::clicked, this, &FindDialog::close);
}
void FindDialog::findClicked()
{
QString text = lineEdit->text();
Qt::CaseSensitivity cs = caseCheckBox->isChecked() ? Qt::CaseSensitive
: Qt::CaseInsensitive;
if (backwardCheckBox->isChecked())
{
qDebug() << 1 << ": " << text << " " << cs;
emit findPrevious(text, cs); // emit关键字,连接signal和slot
}
else
{
qDebug() << 2 << ": " << text << " " << cs;
emit findNext(text, cs);
}
}
void FindDialog::enbaleFindButton(const QString& text)
{
findBtn->setEnabled(!text.isEmpty());
}
三、main函数
#include "finddialog.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
FindDialog w;
w.show();
return a.exec();
}
四、运行结果
五、Dialog窗口布局