QT实现简单四则运算

实现一个简单的四则运算计算器
1.新建项目

点击choose,编辑项目名称,选择存储位置

基类选择widget,选择UI

点击下一步

2.设计UI界面

本例选用6个lineEdit,和一个Label标签

3.选中lineEdit,右键跳转到槽,在此基础上编写代码。
5.点击运行或CTRL+R



4.代码参考
以+法为例,-/*相似
widegt.cpp中声明
+的实现

void Widget::on_pushButton_clicked()
{
    QString str1,str2,str3;
    int a,b,c;
    str1=ui->lineEdit->text();
    str2=ui->lineEdit_2->text();
    a=str1.toInt();
    b=str2.toInt();
    c=a+b;
    str3 = QString::number(c);
    ui->lineEdit_3->setText(str3);
}


/运算
void Widget::on_pushButton_4_clicked()
{
    QString str1,str2,str3;
    int a,b,c;
    str1=ui->lineEdit->text();
    str2=ui->lineEdit_2->text();
    a=str1.toInt();
    b=str2.toInt();
    if(b !=0){
        c=a/b;
        str3 = QString::number(c);
        ui->lineEdit_3->setText(str3);
    }
    else
    {
        QMessageBox::warning(this,"information","wrong");
    }
 
}

6、在.h中
添加#include<QMessageBox>
在private:
        ui::widget *ui;下添加void QMessageBox();
                        
  • 8
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Qt是一个跨平台的C++ GUI应用程序开发框架,提供了许多方便的工具和库,可以帮助开发者快速地开发出高效、美观、易于维护的程序。 关于Qt四则运算的完整代码,以下是一个简单的示例: ```c++ #include <QApplication> #include <QWidget> #include <QLabel> #include <QLineEdit> #include <QPushButton> #include <QGridLayout> int main(int argc, char *argv[]) { QApplication a(argc, argv); QWidget w; QGridLayout *layout = new QGridLayout(&w); // 创建输入框和标签 QLineEdit *input1 = new QLineEdit(&w); QLineEdit *input2 = new QLineEdit(&w); QLabel *plusLabel = new QLabel("+", &w); QLabel *minusLabel = new QLabel("-", &w); QLabel *multiplyLabel = new QLabel("*", &w); QLabel *divideLabel = new QLabel("/", &w); QLabel *equalsLabel = new QLabel("=", &w); QLabel *resultLabel = new QLabel(&w); // 创建按钮 QPushButton *plusButton = new QPushButton("计算", &w); plusButton->setFixedSize(100, 30); // 添加控件到布局中 layout->addWidget(input1, 0, 0); layout->addWidget(plusLabel, 0, 1); layout->addWidget(input2, 0, 2); layout->addWidget(equalsLabel, 0, 3); layout->addWidget(resultLabel, 0, 4); layout->addWidget(plusButton, 1, 4); // 连接计算按钮的点击事件 QObject::connect(plusButton, &QPushButton::clicked, [&]() { int num1 = input1->text().toInt(); int num2 = input2->text().toInt(); int result = num1 + num2; resultLabel->setText(QString::number(result)); }); w.show(); return a.exec(); } ``` 以上代码实现了两个数字的加法运算,并将结果显示在标签中。您可以根据需要修改并添加更多的操作符和计算方式。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值