Qt学习之控件组合封装和自定义信号

Qt学习之控件组合封装和自定义信号 今天学习控件组合封装和自定义信号代码#include QApplication #include QWidget #include QVBoxLayout #include QHBoxLayout #include QLabel #include QLineEdit #include QPushButton #include QMessageBox //#include main.moc // 自定义控件带标签的输入行 class LabeledInput : public QWidget { Q_OBJECT // 自定义信号必须添加此宏 public: LabeledInput(const QString labelText, QWidget *parent nullptr) : QWidget(parent) { QHBoxLayout *layout new QHBoxLayout(this); label new QLabel(labelText); lineEdit new QLineEdit(); label-setFixedWidth(60); layout-addWidget(label); layout-addWidget(lineEdit); layout-setContentsMargins(0,0,0,0); // 转发输入框的文本变化信号 connect(lineEdit, QLineEdit::textChanged, this, LabeledInput::textChanged); } QString text() const { return lineEdit-text(); } signals: void textChanged(const QString text); // 自定义信号 private: QLabel *label; QLineEdit *lineEdit; }; int main(int argc, char *argv[]) { QApplication app(argc, argv); QWidget window; window.setWindowTitle(练习10自定义控件); window.resize(400, 250); QVBoxLayout *layout new QVBoxLayout(window); // 复用自定义控件 LabeledInput *nameInput new LabeledInput(姓名); LabeledInput *phoneInput new LabeledInput(电话); LabeledInput *emailInput new LabeledInput(邮箱); layout-addWidget(nameInput); layout-addWidget(phoneInput); layout-addWidget(emailInput); QPushButton *submitBtn new QPushButton(获取信息); layout-addWidget(submitBtn); QObject::connect(submitBtn, QPushButton::clicked, [](){ QString info QString(姓名%1\n电话%2\n邮箱%3) .arg(nameInput-text()) .arg(phoneInput-text()) .arg(emailInput-text()); QMessageBox::information(window, 信息, info); }); layout-setSpacing(15); layout-setContentsMargins(30, 30, 30, 30); window.show(); return app.exec(); } #include demo10.moc重要方法connect(lineEdit, QLineEdit::textChanged, this, LabeledInput::textChanged)作用信号转发核心技巧。机制当用户在这个输入框中打字时lineEdit会发出textChanged信号。这一行将这个信号连接到LabeledInput自己的textChanged信号上。效果外部使用者只需要监听LabeledInput的textChanged信号就能感知到输入变化而不需要知道内部有个lineEdit。这实现了封装——内部细节对外部透明。QString text() const { return lineEdit-text(); }作用定义一个公有成员函数text()返回当前输入框中的文本。const修饰表示这个函数不会修改类的成员变量。用途在 main 函数中点击按钮时通过nameInput-text()获取用户输入的内容。这是对外暴露的“只读”接口。layout-setSpacing(15)作用设置布局中相邻控件之间的间距为 15 像素。效果三个输入框之间、输入框与按钮之间都会有 15 像素的垂直空隙视觉上更舒展。layout-setContentsMargins(30, 30, 30, 30)作用设置主窗口客户区边缘的内边距为 30 像素左、上、右、下。效果所有控件距离窗口边框有 30 像素的空白不会紧贴边缘看起来更美观。运行结果