温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

控件组合使用C++实例分析

发布时间:2024-09-02 09:35:53 来源:亿速云 阅读:78 作者:小樊 栏目:编程语言

在这个示例中,我们将创建一个简单的C++程序,该程序使用控件组合来实现一个基本的计算器功能。我们将使用以下控件:

  1. 两个文本输入框(用于输入数字)
  2. 一个下拉列表(用于选择操作符)
  3. 一个按钮(用于计算结果)
  4. 一个标签(用于显示结果)

首先,我们需要包含必要的头文件并创建一个主窗口类,该类继承自QWidget

#include <QApplication>
#include <QWidget>
#include <QLineEdit>
#include <QComboBox>
#include <QPushButton>
#include <QLabel>
#include <QHBoxLayout>
#include <QVBoxLayout>

class Calculator : public QWidget {
    Q_OBJECT
public:
    Calculator();
};

接下来,我们需要实现Calculator类的构造函数。在这个构造函数中,我们将创建所需的控件并设置布局。

Calculator::Calculator() {
    // 创建控件
    QLineEdit *number1 = new QLineEdit;
    QLineEdit *number2 = new QLineEdit;
    QComboBox *operatorBox = new QComboBox;
    operatorBox->addItems({"+", "-", "*", "/"});
    QPushButton *calculateButton = new QPushButton("Calculate");
    QLabel *resultLabel = new QLabel;

    // 设置布局
    QHBoxLayout *inputLayout = new QHBoxLayout;
    inputLayout->addWidget(number1);
    inputLayout->addWidget(operatorBox);
    inputLayout->addWidget(number2);

    QVBoxLayout *mainLayout = new QVBoxLayout;
    mainLayout->addLayout(inputLayout);
    mainLayout->addWidget(calculateButton);
    mainLayout->addWidget(resultLabel);

    setLayout(mainLayout);

    // 连接信号和槽
    connect(calculateButton, &QPushButton::clicked, [=]() {
        double num1 = number1->text().toDouble();
        double num2 = number2->text().toDouble();
        QString op = operatorBox->currentText();
        double result = 0;

        if (op == "+") {
            result = num1 + num2;
        } else if (op == "-") {
            result = num1 - num2;
        } else if (op == "*") {
            result = num1 * num2;
        } else if (op == "/") {
            if (num2 != 0) {
                result = num1 / num2;
            } else {
                resultLabel->setText("Error: Division by zero");
                return;
            }
        }

        resultLabel->setText(QString::number(result));
    });
}

最后,我们需要实现main函数来运行应用程序。

int main(int argc, char *argv[]) {
    QApplication app(argc, argv);

    Calculator calculator;
    calculator.show();

    return app.exec();
}

这个简单的C++程序使用Qt框架实现了一个基本的计算器功能。用户可以在文本输入框中输入数字,从下拉列表中选择操作符,然后点击“Calculate”按钮来计算结果。结果将显示在标签中。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

c++
AI