PDA

View Full Version : Passing variable from one form to another



Nicklax
12th November 2016, 06:10
Hello, I am having trouble passing a value from one function in Qt to another in a different form

Beastiary.cpp


void beastiary::on_listWidget_itemClicked(QListWidgetIt em *item)
{
const QString nvalue = ui->listWidget->currentItem()->text(); //Value that needs to passed
read red;
red.setModal(true);
red.exec();
red.ulk();

}


read.cpp


void read::ulk()
{

QFile file (nvalue); //needs nvalue from beastiary so it knows the name of the file to look for
if (!file.open(QFile::ReadOnly | QFile::Text))
{
QMessageBox::warning (this, "Error", "File Could not Be Opened");

}
QString line;
QTextStream in(&file);
while (!in.atEnd())
{
line = in.readLine();
ui->lineEdit_name_r->setText(ui->lineEdit_name_r->text()+line);
qDebug() <<line;
}
}


The variable nvalue must be obtained in beastiary.cpp but is needed in read.cpp and im not sure of how to pass the variable to read from beastiary.

monillo
12th November 2016, 06:24
Hi.
In read.cpp or read.h add variable nvalue (if you like the same name), now in beastiary.cpp before red.exe() assign value to "nvalue", for example: red.nvalue = nvalue.

Hope this help.

Nicklax
12th November 2016, 06:42
Thanks for the reply, I tried your suggestion but got the following error: passing 'const QString' as 'this' argument discards qualifiers [-fpermissive]

This is the code I wrote for it
read.h


#ifndef READ_H
#define READ_H

#include <QDialog>


namespace Ui {
class read;
}

class read : public QDialog
{
Q_OBJECT

friend class beastiary;

public:
const QString nvalue;
void ulk();
explicit read(QWidget *parent = 0);
~read();

private:
Ui::read *ui;

};


#endif // READ_H


beastiary.cpp


void beastiary::on_listWidget_itemClicked(QListWidgetIt em *item)
{
const QString nvalue = ui->listWidget->currentItem()->text();
read red;
red.nvalue=nvalue;
red.setModal(true);
red.exec();
red.ulk();

}


read.cpp



void read::ulk()
{
QFile file (nvalue);
if (!file.open(QFile::ReadOnly | QFile::Text))
{
QMessageBox::warning (this, "Error", "File Could not Be Opened");
}
QString line;
QTextStream in(&file);
while (!in.atEnd())
{
line = in.readLine();
ui->lineEdit_name_r->setText(ui->lineEdit_name_r->text()+line);
qDebug() <<line;
}
}

anda_skoa
12th November 2016, 09:54
You can't assign to a "const" member or variable, it is "constant".

You can keep the const if you pass the value as an argument to read's constructor.

Cheers,
_