Question

I am a student programmer using Qt to develop a GUI application. I am using a QTreeWidget to display some properties stored in a vector. In the same window I have the buttons edit, copy, and delete. So far the buttons work to do what they need to; however I am having an issue when nothing is selected. My program unexpectedly finishes; I am guessing a seg fault. I dont think I am handling the currentItem selected correctly. However Qt's Documentation on this doesn't say what is returned if nothing is selected. So I was hoping for someone with more experience to help/enlighten me on this one. If there is something youd like to see out side of the code included just ask. Here is my (relevant) code:

#include "injectiongui.h"
#include "ui_injectiongui.h"
#include "injectiondialog.h"
#include "ui_injectiondialog.h"
#include "injectiondata.h"
#include <QMessageBox>

InjectionGUI::InjectionGUI(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::InjectionGUI)
{
    ui->setupUi(this);
    ui->groupBoxGlobalParticlesPerCell->hide();
    connect(ui->pushButtonEdit, SIGNAL(clicked()), this, SLOT(slotInjectionEdit()));
}

void InjectionGUI::buildTreeWidget() 
{   
   //Build or Refresh Tree Widget with info from the vector
}

void InjectionGUI::editInjection_Clicked(QTreeWidgetItem *itemToEdit) //Creates an Injection Dialog to edit an Item from the Vector
{
    QString converter = itemToEdit->text(0);
    int id = converter.toInt();
    InjectionDialog editInjectionDialog;
    InjectionData presetValues;
    if(itemToEdit == 0) // this was my attempt to handle nothing selected
    {
        QMessageBox invalidSelection;
        invalidSelection.setText("Error: No row selected to edit");
        return;
    }
    presetValues = qTreeInjectionData.at(id);
    editInjectionDialog.setData(presetValues);
    presetValues = editInjectionDialog.getData();
    editInjectionDialog.exec();
    qTreeInjectionData.replace(id, editInjectionDialog.transInjectionData);
    buildTreeWidget();
}

void InjectionGUI::slotInjectionEdit()
{
    editInjection_Clicked(ui->treeWidgetInjections->currentItem());
}

I tried using qDebug to find out what is being returned but I think its having issues getting the value of the itemToEdit because its a QwidgetTreeItem. Please only leave productive feedback as I am only interested in learning and overcoming the challenge. Thanks in advance!

Was it helpful?

Solution

If no item is selected, you should assume that the currentItem() method returns a NULL pointer:

QString converter = itemToEdit->text(0);

Trying to call a method from a null pointer is undefined behaviour, and it will most likely cause a segmentation fault. So you should add something like:

if(itemToEdit == NULL) {
  // error handling, most likely a simple return
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top