Qt program error

431 views Asked by At

I made following program just for practice in Qt. My program crashes when I click an item in Listwidget so that the row number of that Item becomes an item in Listwidget_2. Here is the code. MainWindow.h is the same as generated by Qt IDE(no changes has been made, all the functions are predefined which have been used in .cpp file). Please also notify if i am making any memory leaks in the program because I am a beginner.

Thanks for your help!

#include "mainwindow.h"
#include "ui_mainwindow.h"

#include <QMessageBox>
#include <QTextStream>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
     ui->setupUi(this);
    noofitems=0;
    files.setFileName("E:/filev.txt");
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::on_actionDelete_Item_triggered()
{

      qDeleteAll(ui->listWidget->selectedItems());
}

void MainWindow::on_okbutton_clicked()
{
    QListWidgetItem *item=new QListWidgetItem;

    item->setText(ui->lineEdit->text());
    ui->listWidget->addItem(item);
    noofitems++;

    writefile();
}

void MainWindow::writefile()
{
    QFile files("E:/legitfile.txt");

    if(files.exists())
    {
        if(!files.open(QFile::Append | QFile::Text))
        {
            QMessageBox::warning(this,"File Access!!!","The File containing data of the         Items and Comments can't be acessed",QMessageBox::Ok);
        }
    }else
        if(!files.open(QFile::WriteOnly | QFile::Text))
        {
            QMessageBox::warning(this,"File Access!!!","The File containing data of the     Items and Comments can't be acessed",QMessageBox::Ok);
        }

    QTextStream out(&files);
    out<< noofitems<<',';

    files.flush();
    files.close();
}

THE PROGRAM CRASHES WHEN THE FOLLOWING FUNCTION IS CALLED

void MainWindow::on_listWidget_itemClicked(QListWidgetItem *item)
{
    QListWidgetItem *itm=new QListWidgetItem;
    itm->setText((char*)(ui->listWidget->currentRow()));
    ui->listWidget_2->addItem(itm);
}
1

There are 1 answers

4
Tim Meyer On BEST ANSWER

Try the following:

void MainWindow::on_listWidget_itemClicked(QListWidgetItem *item)
{
     Q_ASSERT( ui );
     Q_ASSERT( ui->listWidget );
     Q_ASSERT( ui->listWidget_2 );

     QListWidgetItem *itm=new QListWidgetItem;
     itm->setText( QString::number( ui->listWidget->currentRow() ) );
     ui->listWidget_2->addItem(itm);
}

If any of the assertions fires, that means either ui, ui->listWidget or ui->listWidget_2 ist not initialised. Also note how I changed the line which converts currentRow() into a number. This is more readable and I'm not sure if converting the row to (char*) is actually the line which crashes your program