QT5(4)代码实现应用及信号槽实例

一、基于Qt5的代码

除了使用Qt的《设计》来快速添加控件,同样可以使用代码来添加控件。

二、新建项目

在新建项目过程中时取消创建界面,Qt将不会帮我们创建UI代码,需要我们手工添加。
这里写图片描述

三、添加代码

1、在mainwindow.h中添加如下代码:
这里写图片描述

#include <QLabel>
#include <QLineEdit>
#include <QPushButton>
private:
    QLabel *label_1,*label_2;
    QLineEdit *lineEdit_1;
    QPushButton *button_1;

2、在mainwindow.cpp中添加如下控件:
这里写图片描述

    QWidget *cenWidget = new QWidget(this);  //记得在头文件中包括QWidget 
    setCentralWidget(cenWidget);

    label_1 = new QLabel(cenWidget);
    label_1->setText(tr("请输入:"));
    label_2 = new QLabel(cenWidget);
    lineEdit_1 = new QLineEdit(cenWidget);
    button_1 = new QPushButton(cenWidget);
    button_1->setText(tr("显示面积"));

    QGridLayout *mainLayout = new QGridLayout(cenWidget);
    mainLayout->addWidget(label_1, 0, 0);
    mainLayout->addWidget(lineEdit_1, 0, 1);
    mainLayout->addWidget(label_2, 1, 0);
    mainLayout->addWidget(button_1, 1, 1);

    connect(button_1, SIGNAL(clicked()), this, SLOT(showArea())); // 此处是对相应控件绑定clicked事件

3、在mainwindow中添加如下控件:
声明信号槽函数:
这里写图片描述

private slots:
    void showArea();

实现信号槽函数:
这里写图片描述

void MainWindow::showArea(){
    bool ok;
    QString tempStr;
    QString valueStr = lineEdit_1->text();
    int valueInt = valueStr.toInt(&ok);
    double area = valueInt*valueInt*3.14;
    label_2->setText(tempStr.setNum(area));
}

四、注意问题

1、出现 Attempting to add QLayout “” to MainWindow “”, which already has a layout
解决:布局layout新建对象时参数使用this,而mainwindow中其实已存在一个layout。不要使用this
2、在mainwindow中添加多个控件,控件却重叠只显示最后一个。
解决:

Note: Creating a main window without a central widget is not supported. You must have a central widget even if it is just a placeholder.

添加如下代码:

    QWidget *cenWidget = new QWidget(this);  //添加该行
    setCentralWidget(cenWidget);             //添加该行

    label_1 = new QLabel(cenWidget);   //注意参数
    label_1->setText(tr("请输入:"));
    label_2 = new QLabel(cenWidget);   //注意参数
    lineEdit_1 = new QLineEdit(cenWidget);    //注意参数
    button_1 = new QPushButton(cenWidget);    //注意参数
    button_1->setText(tr("显示面积"));

    QGridLayout *mainLayout = new QGridLayout(cenWidget);    //注意参数
    mainLayout->addWidget(label_1, 0, 0);

3、使用信号槽注意事项:
信号函数与槽函数参数类型必须按顺序对应;槽函数参数个数可少于信号函数参数个数,且按顺序对应,多余参数会自动忽略。
发出信号函数:emit iSignal(“信号发出”);
4、connect参数传递解决办法:
// 1、重载相应类的信号函数
// 2、自定义信号函数和槽函数
// 3、直接在类内部定义个成员变量,或者弄个全局变量

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值