编写代码的方式来实现计算圆面积的功能

xiaoxiao2021-02-28  30

这里要把复选框去掉

出现了一个这样的bug,最后查明原因是

点击打开链接

解决方法如下

#include "mainwindow.h" #include <QGridLayout> MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) { QWidget *widget = new QWidget();//新添加的内容 创建一个QWidget实例 this->setCentralWidget(widget); label1 = new QLabel(this); label1->setText(tr("请输入圆的半径: ")); lineEdit = new QLineEdit(this); label2 = new QLabel(this); button = new QPushButton(this); button->setText(tr("显示对应圆的面积")); QGridLayout *mainLayout2 = new QGridLayout(this); widget->setLayout(mainLayout2); mainLayout2->addWidget(label1, 0, 0); mainLayout2->addWidget(lineEdit, 0, 1); mainLayout2->addWidget(label2, 1, 0); mainLayout2->addWidget(button, 1, 1); } MainWindow::~MainWindow() { }

完成后代码及效果图如下所示

mainwindow.h

#ifndef MAINWINDOW_H #define MAINWINDOW_H #include <qlabel.h> #include <QLineEdit> #include <QPushButton> #include <QMainWindow> class MainWindow : public QMainWindow { Q_OBJECT public: MainWindow(QWidget *parent = 0); ~MainWindow(); private: QLabel *label1,*label2; QLineEdit *lineEdit; QPushButton *button; private slots: void showArea(); }; #endif // MAINWINDOW_H

mainwindow.cpp

#include "mainwindow.h" #include <QGridLayout> const static double PI = 3.1416; MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) { QWidget *widget = new QWidget();//新添加的内容 创建一个QWidget实例 this->setCentralWidget(widget); label1 = new QLabel(this); label1->setText(tr("请输入圆的半径: ")); lineEdit = new QLineEdit(this); label2 = new QLabel(this); button = new QPushButton(this); button->setText(tr("显示对应圆的面积")); QGridLayout *mainLayout2 = new QGridLayout(this); widget->setLayout(mainLayout2); mainLayout2->addWidget(label1, 0, 0); mainLayout2->addWidget(lineEdit, 0, 1); mainLayout2->addWidget(label2, 1, 0); mainLayout2->addWidget(button, 1, 1); connect(button, SIGNAL(clicked()), this, SLOT(showArea())); } void MainWindow::showArea() { bool ok; QString tempStr; QString valueStr = lineEdit->text(); int valueInt = valueStr.toInt(&ok); double area = valueInt*valueInt*PI; label2->setText(tempStr.setNum(area)); } MainWindow::~MainWindow() { }
转载请注明原文地址: https://www.6miu.com/read-2630500.html

最新回复(0)