Qt实现计算圆的面积

dialog.h

#ifndef DIALOG_H
#define DIALOG_H

#include <QDialog>

class QLabel;
class QLineEdit;
class QPushButton;
class QGridLayout;

class Dialog : public QDialog
{
    Q_OBJECT

public:
    Dialog(QWidget *parent = 0);
    ~Dialog();

private slots:
    void showArea();

private:
    QLabel *label1, *label2;
    QLineEdit *lineEdit;
    QPushButton *button;
    QGridLayout *mainLayout;
};

#endif // DIALOG_H

dialog.cpp

#include "dialog.h"
#include <QLabel>
#include <QLineEdit>
#include <QPushButton>
#include <QGridLayout>
#include <iostream>

namespace
{
    const static double PI = 3.1416;
}

Dialog::Dialog(QWidget *parent)
    : QDialog(parent)
{
    label1 = new QLabel(this);
    label1->setText(tr("input radius: "));
    lineEdit = new QLineEdit(this);

    label2 = new QLabel(this);
    button = new QPushButton(this);
    button->setText(tr("show area"));

    mainLayout = new QGridLayout(this);
    mainLayout->addWidget(label1, 0, 0);
    mainLayout->addWidget(lineEdit, 0, 1);
    mainLayout->addWidget(label2, 1, 0);
    mainLayout->addWidget(button, 1, 1);

    connect(button, SIGNAL(clicked()), this, SLOT(showArea()));
}

Dialog::~Dialog()
{
    if (label1)
        delete label1;
    if (lineEdit)
        delete lineEdit;
    if (label2)
        delete label2;
    if (button)
        delete button;
    if (mainLayout)
        delete mainLayout;
}

void Dialog::showArea()
{
    QString value = lineEdit->text();

    bool ok;
    int num = value.toInt(&ok);
    if (ok)
    {
        double area = num * num * PI;
        QString str;
        label2->setText(str.setNum(area));
    }
    else
    {
        std::cout << "Hello World, You are failed" << std::endl;
    }
}

main.cpp

#include "dialog.h"
#include <QApplication>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    Dialog w;
    w.show();

    return a.exec();
}

编译脚本 test.pro

#-------------------------------------------------
#
# Project created by QtCreator 2018-09-16T10:15:04
#
#-------------------------------------------------

QT       += core gui

greaterThan(QT_MAJOR_VERSION, 4): QT += widgets

TARGET = test
TEMPLATE = app


SOURCES += main.cpp\
        dialog.cpp

HEADERS  += dialog.h

结果展示:

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值