简体   繁体   English

使用 C++ 读取 Qt GUI 应用程序中的输入和打印阶乘

[英]Read the input and print factorial in Qt GUI Application using C++

Using QTCreator, I created the design of a GUI Application.使用 QTCreator,我创建了一个 GUI 应用程序的设计。 I want to read the input entered by the user from lineEdit and when pushButton is clicked, it should print the factorial of that entered number on the same page.我想读取用户从 lineEdit 输入的输入,当单击 pushButton 时,它应该在同一页面上打印输入数字的阶乘。 I've read some tutorials but don't understand how to code this using qtc++.我已经阅读了一些教程,但不明白如何使用 qtc++ 编写代码。

A minimal example is like that:一个最小的例子是这样的:

mainwindow.h主窗口.h

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QWidget>
#include <QLineEdit>
#include <QPushButton>
#include <QHBoxLayout>
class MainWindow : public QWidget
{
    Q_OBJECT

public:
    MainWindow(QWidget *parent = nullptr);
    ~MainWindow();

private slots:

    void hClicked();
    void hTextEdit(const QString& data);

private:
    QString m_linedata;
    QPushButton button;
    QLineEdit lineEdit;
    QHBoxLayout layout;
};
#endif // MAINWINDOW_H

mainwindow.cpp主窗口.cpp

#include "mainwindow.h"
#include <iostream>

MainWindow::MainWindow(QWidget *parent)
: QWidget(parent)
{
    layout.addWidget(&lineEdit);
    layout.addWidget(&button);
    this->setLayout(&layout);
    connect(&lineEdit, &QLineEdit::textChanged, this, &MainWindow::hTextEdit);
    connect(&button, &QPushButton::clicked, this , &MainWindow::hClicked);
}

MainWindow::~MainWindow()
{

}

static unsigned factorial(unsigned n)
{
    unsigned result = 1;
    for (unsigned i=1; i <= n; i++)  {
        result *= i;
    }
    return  result;
}


void MainWindow::hClicked()
{
    if (m_linedata.size() > 0) {
        bool res ;
        int toint = m_linedata.toInt(&res);
        if (res) {
            unsigned fact_result = factorial(toint);
            lineEdit.clear();
            lineEdit.setText(QString::number(fact_result));        }
    }
}

void MainWindow::hTextEdit(const QString &data)
{
    m_linedata = data;
}

and main.cpp和 main.cpp

#include "mainwindow.h"

#include <QApplication>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    MainWindow w;
    w.show();
    return a.exec();
}

Just do anything you like with the data passed to the auxillary buffer.只需对传递到辅助缓冲区的数据执行任何您喜欢的操作即可。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM