I have established a connection with the slot, the function is called, and the values via qDebug () are output, but the table does not change, what is wrong?
mainwindow.cpp
<pre>MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
ui->tableWidget->horizontalHeader()->hide();
ui->tableWidget->verticalHeader()->hide();
//Matrix *matr=new Matrix;
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::on_updateTbl(int **mas, int n){
for(int i=0;i<n;i++){
ui->tableWidget->insertRow(ui->tableWidget->rowCount());
for(int j=0;j<n;j++){
ui->tableWidget->insertColumn(ui->tableWidget->columnCount());
ui->tableWidget->setItem(i,j,new QTableWidgetItem( QString::number(mas[i][j])));
}
}
}
</pre>
main.cpp
<pre>
#include "mainwindow.h"
#include <QApplication>
#include "matrix.h"
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.show();
Matrix matr;
MainWindow mywnd;
QObject::connect(&matr,SIGNAL(updateTbl(int**,int)), &mywnd, SLOT(on_updateTbl(int**,int)));
matr.upTable();
return a.exec();
}
</pre>
matrix.cpp
<pre>
#include "matrix.h"
#include <QFile>
#include <QDebug>
#include <QString>
#include <QTextStream>
Matrix::Matrix()
{
QFile file("mas.txt");
this->mas=alloc_mem(n,n);
array_to_file(file,n,n);
fill_array(file,mas,n,n);
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
if (mas[i][j]!=mas[n-j-1][n-i-1]) {
symmetrical=false;
break;
}
}
}
if(symmetrical){
for(int i=0;i<n;i++){
mas[i][i]=0;
mas[i][n-i-1]=0;
}
//print(mas,n,"Измененная");
}
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
if(mas[i][j]) vec.append(mas[i][j]);
}
}
}
int** Matrix::alloc_mem(int height, int width){
int** mas = new int*[height];
for (int i = 0; i < height; i++) {
mas[i] = new int[width];
}
return mas;
}
void Matrix::array_to_file(QFile &file, int height, int width){
if (!file.open(QIODevice::WriteOnly | QIODevice::Text))
return;
int to_mas;
QTextStream out(&file);
for (int i = 0; i < height; i++){
for (int j = i + 1; j < width; j++){
to_mas=rand()%100-50;
out<<to_mas<<" ";
}
out<<1<<" ";
out<<"\n";
}
file.close();
}
void Matrix::fill_array(QFile &file, int **mas, int height, int width){
if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
return;
QTextStream in(&file);
QStringList matr = in.readAll().split("\n");
for (int i = 0; i < height; i++){
for (int j = 0; j < width-i; j++){
mas[i][j]=matr.at(i).split(" ").at(j).toInt();
mas[height-1-j][width-1-i]=mas[i][j];
}
}
file.close();
}
void Matrix::print(int **mas, int n, QString name){
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
}
}
}
void Matrix::upTable(){
emit updateTbl(mas,n);
}
</pre>
mainwindow.h
<pre>
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
private:
Ui::MainWindow *ui;
private slots:
void on_updateTbl(int**,int);
};
#endif // MAINWINDOW_H
</pre>
matrix.h
<pre>
#ifndef MATRIX_H
#define MATRIX_H
#include <QVector>
#include <QFile>
#include <QString>
#include <QObject>
class Matrix:public QObject
{
Q_OBJECT
public:
Matrix();
~Matrix(){}
//bool check_symmetrical(int **mas,int n);
void print_vector(QVector<int> vector);
int** alloc_mem(int height,int width);
void array_to_file(QFile& file,int height,int width);
void fill_array(QFile& file,int **mas,int height,int width);
void print(int** mas,int n,QString name);
void upTable();
private:
int n=10;
int **mas;
bool symmetrical=true;
QVector<int> vec;
signals:
void updateTbl(int**,int);
};
#endif // MATRIX_H
</pre>
If I copy this code into the constructor, then everything is fine and everything changes, but nothing works from the function
How do you want to see table with values when widget with updated table is not displayed?
MainWindow w;
w.show(); // <--- w is displayed, tableWidget is not modified in this widget
Matrix matr;
MainWindow mywnd; // <--- mywnd is not displayed
QObject::connect(&matr,SIGNAL(updateTbl(int**,int)), &mywnd, SLOT(on_updateTbl(int**,int)));
// mywnd is updated
matr.upTable();
add
mywnd.show();
you will see the other widget with updated content.
Related
I'm new in Qt. I have got Class TicTacToeWidget which stores QList with QPushButton.
int m_size is initialized with 3 and works fine and i see 3x3 board, but when i try to change m_size in main.cpp to other value nothing happends. I can't find out why it doesn't work.
#ifndef TICTACTOEWIDGET_H
#define TICTACTOEWIDGET_H
#include <QWidget>
class QPushButton;
class TicTacToeWidget : public QWidget
{
Q_OBJECT
public:
TicTacToeWidget(QWidget *parent = 0);
~TicTacToeWidget();
int size()const;
void resizeBoard(int m);
private:
QList<QPushButton *> m_board;
int m_size;
void setupBoard(int m);
void clearBoard();
};
#endif // TICTACTOEWIDGET_H
And implementation
#include "tictactoewidget.h"
#include <QMessageBox>
#include <QGridLayout>
#include <QPushButton>
#include <QDebug>
TicTacToeWidget::TicTacToeWidget(QWidget *parent)
: QWidget(parent),m_size(3)
{
setupBoard(3);
}
TicTacToeWidget::~TicTacToeWidget()
{
}
int TicTacToeWidget::size() const
{
return m_size;
}
void TicTacToeWidget::resizeBoard(int m)
{
setupBoard(m);
}
void TicTacToeWidget::setupBoard(int m)
{
QGridLayout *gridLayout= new QGridLayout;
m_size=m;
m_board.clear();
for(int i=0;i<m_size;i++)
{
for(int j=0;j<m_size;j++)
{
QPushButton *button= new QPushButton;
button->setSizePolicy(QSizePolicy::Minimum,QSizePolicy::Minimum);
button->setText(" ");
gridLayout->addWidget(button,i,j);
}
}
setLayout(gridLayout);
}
void TicTacToeWidget::clearBoard()
{
for(auto &it:m_board)
{
this->layout()->removeWidget(it);
}
m_board.clear();
}
And main
#include "tictactoewidget.h"
#include <QApplication>
using namespace std;
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
TicTacToeWidget w;
w.resizeBoard(5);
w.show();
return a.exec();
}
http://doc.qt.io/qt-4.8/qwidget.html#setLayout
If there already is a layout manager installed on this widget, QWidget won't let you install another. You must first delete the existing layout manager
I am working on a matrix calculator and I encountered a really annoying problem, have been trying to fix it for 3 hours now, but it's getting worse instead of getting better. Maybe you will be able to help.
This is my MainWindow class:
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QPushButton>
#include <QGridLayout>
#include <QLabel>
#include "addmatrix.h"
#include "memory.h"
#include "matrixcreation.h"
#include <QMap>
#include "matrix.h"
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(MainWindow *parent = 0);
~MainWindow();
private slots:
void on_createButton_clicked();
void setMatrix(Matrix *matrix);
private:
Matrix getMatrixFromMemory(QString &name);
void addMatrixToMemory();
Ui::MainWindow *ui;
AddMatrix *add;
MatrixCreation *matrixCreate;
QMap <QString, Matrix> matrixMap;
};
#endif // MAINWINDOW_H
.cpp file
#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(MainWindow *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
this->setWindowTitle("Matrix Calculator");
add = NULL;
matrixCreate = NULL;
}
MainWindow::~MainWindow()
{
delete ui;
delete add;
delete matrixCreate;
matrixMap.clear();
}
void MainWindow::on_createButton_clicked()
{
if (add != NULL)
{
delete add;
add = new AddMatrix;
}
else
add = new AddMatrix;
if (matrixCreate != NULL)
{
ui->label->setText(getMatrixFromMemory(matrixCreate->getMatrix()->getName()).getName());
delete matrixCreate;
matrixCreate = new MatrixCreation;
}
else
matrixCreate = new MatrixCreation;
// Polaczenie sygnalow ze slotami
// Sluzy ustawieniu liczby wierszy w matrixCreate
connect(add->getCombo1(), SIGNAL(currentIndexChanged(QString)), matrixCreate, SLOT(setRows(QString)));
// Jak wyzej, tylko kolumn
connect(add->getCombo2(), SIGNAL(currentIndexChanged(QString)), matrixCreate, SLOT(setColumns(QString)));
// Ustawienie pola name w matrixCreate
connect(add->getEdit(), SIGNAL(textChanged(QString)), matrixCreate, SLOT(setName(QString)));
// Po ustawieniu liczby wierszy i kolumn oraz nazwy macierzy - wywola sie slot updateTable
// ktory sluzy do ustawienia rozmiaru okna i tabeli
connect(add, SIGNAL(setupSuccessful()), matrixCreate, SLOT(updateTable()));
// Po ustawieniu wierszy, kolumn, ustawieniu nazwy, rozmiarow, wywola sie slot show matrixCreate
connect(add, SIGNAL(setupSuccessful()), matrixCreate, SLOT(show()));
// Sluzy dodaniu macierzy do pamieci (mapy)
connect(matrixCreate, SIGNAL(matrixReady(Matrix*)), this, SLOT(setMatrix(Matrix*)));
add->show();
}
void MainWindow::setMatrix(Matrix *matrix)
{
matrixMap[matrix->getName()] = *matrix;
}
Matrix MainWindow::getMatrixFromMemory(QString &name)
{
return matrixMap[name];
}
As you can see I have a QMap in my MainWindow. I also have a an instance of MatrixCreation class called matrixCreate.
Here is MatrixCreation class:
#ifndef MATRIXCREATION_H
#define MATRIXCREATION_H
#include <QDialog>
#include <QTableView>
#include <QPushButton>
#include <QStandardItem>
#include <QTableWidget>
#include <QMainWindow>
#include "matrix.h"
#include "memory.h"
#include "addmatrix.h"
#include <windows.h>
namespace Ui {
class MatrixCreation;
}
class MatrixCreation : public QWidget
{
Q_OBJECT
public:
explicit MatrixCreation(QWidget *parent = 0);
~MatrixCreation();
QTableWidget *getTable();
Matrix *getMatrix();
private slots:
void on_okButton_clicked();
void updateTable();
void setRows(QString rows);
void setColumns(QString columns);
void setName(QString name);
signals:
void matrixReady(Matrix *matrix);
private:
Ui::MatrixCreation *ui;
int rows;
int columns;
int **matrix;
QString name;
Matrix *newMatrix;
};
#endif // MATRIXCREATION_H
.cpp file
#include "matrixcreation.h"
#include "ui_matrixcreation.h"
MatrixCreation::MatrixCreation(QWidget *parent) :
QWidget(parent),
ui(new Ui::MatrixCreation)
{
ui->setupUi(this);
this->resize(150, 50);
// Ustawienie rozmiaru wysokosci wiersza na 40 piksele
ui->tableWidget->verticalHeader()->setDefaultSectionSize(40);
// Ustawienie rozmiaru szerokosci kolumny na 94 piksele
ui->tableWidget->horizontalHeader()->setDefaultSectionSize(94);
// Dopasowanie rozmiaru kolumn do rozmiaru tabeli
ui->tableWidget->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
ui->tableWidget->verticalHeader()->setSectionResizeMode(QHeaderView::Stretch);
// Wylaczenie scrollbarow tabeli
ui->tableWidget->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
ui->tableWidget->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
rows = 1;
columns = 1;
matrix = NULL;
newMatrix = new Matrix;
}
MatrixCreation::~MatrixCreation()
{
delete ui;
if (matrix != NULL)
{
for (int i = 0; i < rows; i++)
delete matrix[i];
}
delete newMatrix;
}
void MatrixCreation::setRows(QString rows)
{
this->rows = rows.toInt();
}
void MatrixCreation::setColumns(QString columns)
{
this->columns = columns.toInt();
}
// Metoda odpowiedzialna za utworzenie odpowiedniej ilosci wierszy i kolumn
// oraz ustawienie odpowiedniej wielkosci okna i rozmiaru tabeli
void MatrixCreation::updateTable()
{
// stale roznice miedzy szerokoscia i wysokoscia okna i tabeli
int w = 323 - 305;
int h = 300 - 227 + 15;
for(int i = 0; i < rows; i++)
{
ui->tableWidget->insertRow(i);
h += 35;
}
for(int j = 0; j < columns; j++)
{
ui->tableWidget->insertColumn(j);
w += 50;
}
this->resize(w, h);
this->setMinimumSize(w, h);
ui->retranslateUi(this);
this->setWindowTitle("Matrix Creation");
}
QTableWidget *MatrixCreation::getTable()
{
return ui->tableWidget;
}
void MatrixCreation::on_okButton_clicked()
{
matrix = new int *[rows];
for(int j = 0; j < rows; j++)
{
matrix[j] = new int[columns];
}
for(int i = 0; i<rows; i++)
{
for(int j = 0; j<columns; j++)
{
matrix[i][j] = ui->tableWidget->item(i, j)->text().toInt();
}
}
// Ustawienie pol skladowych w zmiennej newMatrix klasy Matrix
newMatrix->setColumns(columns);
newMatrix->setRows(rows);
newMatrix->setName(name);
newMatrix->setMatrix(matrix);
emit matrixReady(newMatrix);
this->close();
}
void MatrixCreation::setName(QString name)
{
this->name = name;
}
Matrix *MatrixCreation::getMatrix()
{
return newMatrix;
}
What is the problem:
I want to add a created matrix to a QMap by emiting this signal:
emit matrixReady(newMatrix);
a Matrix class is used to hold all the elements of matrix (rows, cols, values of cells and name).
However, Matrix objects are not being added to QMap. But, when I delete this line in MatrixCreation destructor:
delete newMatrix;
It works.
Second problem:
When I am closing my application and MainWindow destructor gets called, while destroying a map it shows an error : BLOC_TYPE_IS_VALID bla bla...
I don't know how to fix it, however I will keep on trying. Any help will be appreciated.
void MainWindow::setMatrix(Matrix *matrix)
{
matrixMap[matrix->getName()] = *matrix;
}
You're adding copy of the matrix to your map. So here you have a leak.
void MainWindow::setMatrix(Matrix *matrix)
{
matrixMap[matrix->getName()] = *matrix;
delete matrix;
}
This should fix your problem.
Use valgrind to profile your application and find memory leaks: http://valgrind.org/docs/manual/quick-start.html
I have created a simple calculator in Qt , however I am trying to add a button to do me a factorial but its not working
can someone help me with it ?
I already have a method factorial implemented
#include "mainwindow.h"
#include <QtCore/QCoreApplication>
QString value="",total="";
double fNum,sNum;
bool addBool=false, substractBool=false, multiplyBool=false, divideBool=false,Factorbool=false;
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent)
{
label=new QLabel("0",this);
label->setGeometry(QRect(QPoint(75,25),QSize(50,200)));
clear_button=new QPushButton("C",this);
clear_button->setGeometry(QRect(QPoint(50,300),QSize(50,50)));
connect(clear_button,SIGNAL(released()),this,SLOT(clear()));
equals_button=new QPushButton("=",this);
equals_button->setGeometry(QRect(QPoint(100,300),QSize(50,50)));
connect(equals_button,SIGNAL(released()),this,SLOT(equals()));
add_button=new QPushButton("+",this);
add_button->setGeometry(QRect(QPoint(200,150),QSize(50,50)));
connect(add_button,SIGNAL(released()),this,SLOT(add()));
Factor_button =new QPushButton("n!",this);
Factor_button->setGeometry(QRect(QPoint(250,150),QSize(50,50)));
connect(Factor_button ,SIGNAL(released()),this,SLOT(add()));
substract_button=new QPushButton("-",this);
substract_button->setGeometry(QRect(QPoint(200,200),QSize(50,50)));
connect(substract_button,SIGNAL(released()),this,SLOT(substract()));
multiply_button=new QPushButton("X",this);
multiply_button->setGeometry(QRect(QPoint(200,250),QSize(50,50)));
connect(multiply_button,SIGNAL(released()),this,SLOT(multiply()));
divide_button=new QPushButton("/",this);
divide_button->setGeometry(QRect(QPoint(200,300),QSize(50,50)));
connect(divide_button,SIGNAL(released()),this,SLOT(divide()));
for(int i=0;i<10;i++){
QString digit=QString::number(i);
buttons[i]=new QPushButton(digit,this);
connect(buttons[i],SIGNAL(released()),this,SLOT(buttonPushed()));
}
setGeo();
}
void MainWindow::setGeo()
{
for(int i=0;i<1;i++)
{
buttons[i]->setGeometry(QRect(QPoint(50,300),QSize(50,50)));
}
for(int i=0;i<4;i++)
{
buttons[i]->setGeometry(QRect(QPoint(50*i,250),QSize(50,50)));
}
for(int i=4;i<7;i++)
{
buttons[i]->setGeometry(QRect(QPoint(50*(i-3),200),QSize(50,50)));
}
for(int i=7;i<10;i++)
{
buttons[i]->setGeometry(QRect(QPoint(50*(i-6),150),QSize(50,50)));
}
}
void MainWindow::buttonPushed()
{
QPushButton *button=(QPushButton *)sender();
emit numberEnitted(button->text()[0].digitValue());
value+=QString::number(button->text()[0].digitValue());
label->setText(value);
}
void MainWindow::clear(){
value="";
label->setText(value);
}
void MainWindow::add(){
fNum=value.toDouble();
value="";
label->setText(value);
addBool=true;
}
int factorial( int n)
{
if (n == 0)
return 1;
return n * factorial(n - 1);
}
void MainWindow::equals(){
sNum=value.toDouble();
if(addBool){
total=QString::number(fNum+sNum);
label->setText(total);
}
if(substractBool){
total=QString::number(fNum-sNum);
label->setText(total);
}
if(multiplyBool){
total=QString::number(fNum*sNum);
label->setText(total);
}
if(divideBool){
total=QString::number(fNum/sNum);
label->setText(total);
}
if(Factorbool)
{
total=QString::number(factorial(fNum));
label->setText(total);
}
}
void MainWindow::substract(){
fNum=value.toDouble();
value="";
label->setText(value);
substractBool=true;
}
void MainWindow::multiply(){
fNum=value.toDouble();
value="";
label->setText(value);
multiplyBool=true;
}
void MainWindow::divide(){
fNum=value.toDouble();
value="";
label->setText(value);
divideBool=true;
}
void MainWindow::Factor(){
fNum=value.toDouble();
value="";
label->setText(value);
Factorbool=true;
}
MainWindow::~MainWindow()
{
}
The Main
#include "mainwindow.h"
#include <QApplication>
#include <QDesktopWidget>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.showMaximized();
w.setFixedSize(300,400);
w.move(QApplication::desktop()->screen()->rect().center()-w.rect().center());
w.show();
return a.exec();
}
The .h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QPushButton>
#include <QLabel>
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
signals:
void numberEnitted(int number);
private slots:
void clear();
void add();
void equals();
void substract();
void multiply();
void divide();
void Factor();
void buttonPushed();
void setGeo();
private:
QLabel *label;
QPushButton *clear_button;
QPushButton *add_button;
QPushButton *equals_button;
QPushButton *substract_button;
QPushButton *multiply_button;
QPushButton *Factor_button;
QPushButton *divide_button;
QPushButton *zero_button;
QPushButton *buttons[10];
};
#endif
I am awaiting your help :)
The signal that is fired when you press the Factor_button is not connected to the correct slot.
This line
connect(Factor_button, SIGNAL(released()), this, SLOT(add()));
should be
connect(Factor_button, SIGNAL(released()), this, SLOT(Factor()));
I have a problem with MathGL library and creating MathGL instance in the application. Every time I try to run it there is an error saying that QApplication must be constructed before QWidget (from which the class QMathGL inherits). Below you can find my code of main and all the functions connected with the MainWindow class:
mainwindow.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "functions.h"
#include "surface.h"
#include "error.h"
#include <QString>
#include <QFileDialog>
#include <GL/glut.h>
#include <cmath>
#include <fstream>
#include <mgl2/qmathgl.h>
surface graph;
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::on_draw_clicked()
{
string s;
bool correct = 1;
error *errorWindow = new error(this);
s = ui->eqEdit->text().toStdString();
period fPeriod = period(ui->upEdit->text().toDouble(),ui->lowEdit->text().toDouble());
functionSum fSum = functionSum(s,fPeriod,ui->accEdit->text().toDouble());
for (int i = 0; i < fSum.accuracy; i++)
{
for (int j = 0; j < fSum.accuracy; j++)
{
if(isnan(fSum.zValues[i][j]) || isinf(fSum.zValues[i][j]))
{
correct = 0;
}
}
}
if(!correct)
{
errorWindow->show();
}
graph = surface(fSum);
}
void MainWindow::on_save_clicked()
{
QString plik;
string splik;
plik = QFileDialog::getSaveFileName(this,"Zapisz plik",QString(),"Pliki tekstowe (*.txt)");
splik = plik.toStdString();
ofstream saver;
saver.open(splik.c_str());
if (saver.is_open())
{
for(int i = 0; i < graph.points.size(); i++)
{
saver << graph.points[i].x << " " << graph.points[i].y << " " << graph.points[i].z << endl;
}
saver.close();
}
}
void MainWindow::on_load_clicked()
{
QString plik;
string splik;
plik = QFileDialog::getOpenFileName(this,"Otwórz plik",QString(),"Pliki tekstowe (*.txt)");
splik = plik.toStdString();
ifstream loader;
loader.open(splik.c_str());
graph.points.clear();
if(loader.is_open())
{
while(!loader.eof())
{
point a(0,0,0);
loader >> a.x >> a.y >> a.z;
graph.points.push_back(a);
}
loader.close();
}
}
void MainWindow::on_plot_clicked()
{
int a = sqrt(graph.points.size());
mglData x(a,a);
mglData y(a,a);
mglData z(a,a);
long long int k = 0;
for (long long int i = 0;i<sqrt(graph.points.size());i++)
{
for (long long int j = 0;j<sqrt(graph.points.size());j++)
{
x.a[i+a*j] = graph.points[k].x;
y.a[i+a*j] = graph.points[k].y;
z.a[i+a*j] = graph.points[k].z;
k++;
}
}
mglGraph plot;
plot.Rotate(50,60);
plot.Light(true);
plot.Surf(x,y,z);
QMathGL plotter;
plotter.setGraph(&plot);
plotter.show();
}
main.cpp
#include "mainwindow.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.show();
return a.exec();
}
This question already has an answer here:
Qt/C++ Convert QString to Decimal
(1 answer)
Closed 8 years ago.
I am trying to make a program that takes 3 user inputs and a calculate button that puts them all into an equation and prints out the answer. The problem I am having right now is that the inputs seem to not be able to convert to numbers and I can't figure out why.
Error reads on line (int numN0 = QString::number(N0);):
error: no matching function for call to 'QString::number(QString&)'
Here's my code:
Header
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
private slots:
void on_NtButton_clicked();
void on_N0Button_clicked();
void on_kButton_clicked();
void on_tButton_clicked();
void on_quitButton_clicked();
void on_pushButton_5_clicked();
void on_equation_linkActivated(const QString &link);
private:
Ui::MainWindow *ui;
int N;
int N0;
int k;
int t;
};
Main.cpp
#include "mainwindow.h"
#include <QApplication>
#include <QPushButton>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
/*QPushButton *button = new QPushButton("Quit the program!");
QObject::connect(button, SIGNAL(clicked()), &app, SLOT(quit()));
button->show();
*/
MainWindow w;
w.show();
return a.exec();
}
mainwindow.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QtCore>
#include <QtGui>
#include <QMessageBox>
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::on_N0Button_clicked()
{
QString N0 = ui->lineEdit_2->text();
int numN0 = QString::number(N0);
if (numN0 < 1000){
QMessageBox::information(this,"Error","Can't be over 1000");
}
if (ui->lineEdit_2->text() > 0)
{
QMessageBox::information(this,"Error","Can't be under 0");
}
}
void MainWindow::on_kButton_clicked()
{
int k = ui->lineEdit_3->text();
if (QString::number(k) > 1)
{
QMessageBox::information(this,"Error","Can't be over 1");
}
if (ui->lineEdit_3->text() < 0)
{
QMessageBox::information(this,"Error","Can't be under 0");
}
}
void MainWindow::on_tButton_clicked()
{
QString t = ui->lineEdit_4->text();
}
void MainWindow::on_pushButton_5_clicked()
{
for (int x = 0; x < t; x++)
{
int ans = N*x == N0*10^(k*x);
ui->equation->setText(QString::number(ans));
}
}
You should use:
QString N0 = ui->lineEdit_2->text();
int numN0 = N0.toInt();
QString::number(N0) takes int and return QString, but you need conversion to int. Also you can use bool ok if you want to know is conversion was successful.
For example:
QString str = "FF";
bool ok;
int hex = str.toInt(&ok, 16); // hex == 255, ok == true
int dec = str.toInt(&ok, 10); // dec == 0, ok == false
Information