-1

Using QTCreator, I created the design of a GUI Application. 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. I've read some tutorials but don't understand how to code this using qtc++.

eyllanesc
  • 235,170
  • 19
  • 170
  • 241
Aiswarya
  • 3
  • 1

1 Answers1

0

A minimal example is like that:

mainwindow.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

#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

#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.

Ilian Zapryanov
  • 1,132
  • 2
  • 16
  • 28