PDA

View Full Version : Segmentation fault while passing IO/file handles



xfurrier
19th August 2009, 00:22
I'm not quite sure what can be done with file/IO handles - can they be copied, passed as an argument, etc. I have to be honest, these are still not completely clear to me despite my efforts to understand it.

I've attached a sample program to get a better idea what I'm trying to do.

In my program I want to select a csv file (FileSelect) and pass a handle to another class (MyDialog). The file might have headers it its first row (name,surname,eid) or not - that info is provided by a user by (un)ticking a checkbox.

Bits in MyDialog constructor (init headers) work as I want. However, I cannot pass 'stop 2' in setHeaders as I get "Segmentation fault".

Any help would be appreciated. Thanks.



#include "mydialog.h"

MyDialog::MyDialog(QWidget *parent, QIODevice *handle) : QDialog(parent)
{
m_handle = handle;

// get the number of columns
QTextStream in(m_handle);
m_nColumns = in.readLine().split(',').length();
qDebug() << "Number of Columns" << m_nColumns;

QCheckBox *checkbox = new QCheckBox("&Header row", this);
checkbox->setCheckState(Qt::Checked);

// init headers - works fine
m_tableWidget = new QTableWidget(0, m_nColumns);
in.seek(0);
QStringList headers = in.readLine().split(',');
m_tableWidget->setHorizontalHeaderLabels(headers);

QVBoxLayout *mainLayout = new QVBoxLayout;
mainLayout->addWidget(checkbox);
mainLayout->addWidget(m_tableWidget);
setLayout(mainLayout);

connect (checkbox, SIGNAL(stateChanged(int)), this, SLOT(headerRowStateChanged(int)));
}


void MyDialog::headerRowStateChanged(int nState)
{
qDebug() << "Checkbox state changed" << nState;

if (nState == Qt::Unchecked)
setHeaders(false);
else if (nState == Qt::Checked)
setHeaders(true);

return;
}

void MyDialog::setHeaders(bool bHeaderRow)
{
QStringList headers;

qDebug() << "stop 1";
if (bHeaderRow) {
qDebug() << "stop 2";
QTextStream in(m_handle);
qDebug() << "stop 3";
QStringList headers = in.readLine().split(',');
qDebug() << "stop 4";
} else {
for (int i = 0; i < m_nColumns; i++)
headers << QString::number(i+1);
}
qDebug() << "stop 5";

m_tableWidget->setHorizontalHeaderLabels(headers);
qDebug() << "stop 6" << headers;

return;
}

spirit
19th August 2009, 06:57
the problem was in that you created QFile in the stack, try this


void FileSelect::processFile()
{
QString strFilename = QFileDialog::getOpenFileName(this, "Select CSV File", ".", "Comma Separated Values (*.csv)");
qDebug() << "got filename" << strFilename;

QFile *file = new QFile(strFilename, this);
if (!file->open(QIODevice::ReadOnly)) {
qDebug() << "cannot read" << strFilename;
return;
}

MyDialog *a = new MyDialog(this, file);
a->show();

return;
}

xfurrier
19th August 2009, 09:32
You're absolutely right. Thanks.