Qt实现计算圆的面积

版权声明:本文为博主原创文章,如有需要,可以随意转载,请注明出处。 https://blog.csdn.net/xunye_dream/article/details/82721621

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

结果展示:

猜你喜欢

转载自blog.csdn.net/xunye_dream/article/details/82721621