【Qt实例】控件和信号槽应用

实例展示

在这里插入图片描述

详情

  • 运行工程后,在 lineEdit 中输入特定限制的字符,经验证后 lineEdit 传出文本改变信号,触发自定义的槽函数,进一步决定是否启用 okButton 按钮;
  • 两个按钮按下后会分别触发 QDialog 类的accept() 和 reject() 槽函数,结果都将使得关闭 dialog 窗口;

ui 界面部件

  • 建立工程时,选择 QDialog 基类
  • label 标签
  • lineEdit 行编辑框
  • Horizontal Spacer 水平间隔
  • pushButton(ok、cancel) 按钮2个
    在这里插入图片描述
    具体布局设计参考,也可忽略掉,这暂时不重要
    在这里插入图片描述

dialog.h文件

#ifndef DIALOG_H
#define DIALOG_H

#include <QDialog>
#include <QRegExpValidator>

QT_BEGIN_NAMESPACE
namespace Ui { class Dialog; }
QT_END_NAMESPACE

class Dialog : public QDialog
{
    Q_OBJECT

public:
    Dialog(QWidget *parent = nullptr);
    ~Dialog();
private slots:
    void on_lineEdit_textChanged();     // 文本框中文本改变槽函数
private:
    Ui::Dialog *ui;
};
#endif // DIALOG_H

dialog.cpp

实例中,已经将 label 和 lineEdit 建立了伙伴部件关系,在 ui 界面初始化时自动将会生成信号和槽的连接函数,即
connect(ui->lineEdit,SIGNAL(textChanged(QString)),this,SLOT(on_lineEdit_textChanged()));
如果没有建立伙伴关系的话,就要写出上述 connect 连接函数。

#include "dialog.h"
#include "ui_dialog.h"

Dialog::Dialog(QWidget *parent)
    : QDialog(parent)
    , ui(new Ui::Dialog)
{
    //初始化,产生界面后根据命名习惯对槽函数进行连接(事先要是伙伴部件关系)
    ui->setupUi(this); 

    QRegExp regExp("[A-Za-z][1-9][0-9]{0,2}");  //正则表达式限制输入子元的范围
    //QRegExpValidator 类利用正则表达式来验证输入字符串是无效/中间/可接受的
    ui->lineEdit->setValidator(new QRegExpValidator(regExp, this));

    connect(ui->okButton, SIGNAL(clicked()), this, SLOT(accept()));
    connect(ui->cancelButton, SIGNAL(clicked()), this, SLOT(reject()));
}

Dialog::~Dialog()
{
    delete ui;
}

void Dialog::on_lineEdit_textChanged()
{
    // 槽函数根据再 lineEdit 中输入的文字是否有效来启用或停用"OK"按钮
    ui->okButton->setEnabled(ui->lineEdit->hasAcceptableInput());
}
  • 9
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值