Search code examples
c++qtsignals-slotsqt-signals

Sending QStringList between classes using signals and slots


I have a GUI built using the QT Creator. At some point a Dialog window is opened to which I need to send a variable of type QStringList. I do this using the signals and slots method. However, the variable is empty once sent. Here is some code samples:

widget.h

class Widget : public QWidget
{
Q_OBJECT
public:
explicit Widget(QWidget *parent = 0);
~Widget();
signals:
void mySignal(QStringList);
};

widget.cpp

Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
 // blah blah
}

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

  void Widget::on_pushButton_4_clicked()
{
    QStringList dList;
    int damount = ui->listWidget->count();
    for(int i=0; i < damount; i++){
                                    dList << ui->listWidget->item(i)->text();
                                    qDebug() << dList;
                                    }
    emit mySignal(dList);

    mysaver mDialog;
    mDialog.setModal(true);
    mDialog.exec();
}

mysaver.h (The dialog box)

class mysaver : public QDialog
{
Q_OBJECT
public:
explicit mysaver(QWidget *parent = 0);
~mysaver();

public slots:
void myreciever(QStringList);
}

mysaver.cpp

void mysaver::myreciever(QStringList aList)
{
qDebug << aList;
}

main.cpp

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
Widget w;

Widget *duff = new Widget;
mysaver *buff = new mysaver;
QObject::connect(duff,SIGNAL(mySignal(QStringList)),buff,SLOT(myreciever(QStringList)));

w.show();

return a.exec();
}

I'd really appreciate some help on this. Note: If I'm doing this whole method wrong and should be doing something entirely different then TELL ME!


Solution

  • You are creating two mysaver instances and only connecting to the first (invisible) one:

    // In main.cpp
    mysaver *buff = new mysaver;
    
    // In Widget::on_pushButton_4_clicked()
    mysaver mDialog;
    mDialog.setModal(true);
    mDialog.exec();
    

    mDialog is not the mysaver instance you connected to.