Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to connect signal to a function inside main()

I am aware that to use the signals and slots mechanism of Qt inside a class, the class must include the Q_OBJECT macro, but I am attempting to use signals and slots in main(), without using any class.

Here is my code so far:

#include <QApplication>
#include <QWidget>
#include <QTextEdit>
#include <QtGui>

void saveText();

int main(int argv, char **args)
 {
    QApplication app(argv, args);
    QTextEdit textEdit;
    QPushButton saveButton("Save!");
    QPushButton exitButton("Exit!");
    QObject::connect(&exitButton,SIGNAL(clicked()),qApp,SLOT(quit()));
    QObject::connect(&saveButton,SIGNAL(clicked()),qApp,SLOT(saveText()));

    QVBoxLayout vlyt;
    vlyt.addWidget(&textEdit);
    vlyt.addWidget(&exitButton);
    vlyt.addWidget(&saveButton);

    QWidget mainWindow;
    mainWindow.setLayout(&vlyt);
    mainWindow.show();

    return app.exec();
}

void saveText()
{
    exit(0);
}

Here is the GUI window generated:

GUI window

From the above code, the exit button is connected to quit(), which is a Qt function, when clicked it works. The save button assigned to the function saveText(), is configured to exit, but does not do so.

Please tell me where I have gone wrong in understanding signals and slots in Qt.

like image 584
CodeCrusader Avatar asked May 24 '13 12:05

CodeCrusader


1 Answers

I'll just put example here.

main.cpp:

#include <QCoreApplication>
#include <iostream>
#include <QObject>
#include "siggen.h"

void handler(int val){
  std::cout << "got signal: " << val << std::endl;
}

int main(int argc, char *argv[])
{
  SigGen siggen;
  QObject::connect(&siggen, &SigGen::sgAction, handler);
  siggen.action();

  QCoreApplication a(argc, argv);
  std::cout << "main prog start" << std::endl;

  return a.exec();
}

siggen.h:

#ifndef SIGGEN_H
#define SIGGEN_H

#include <QObject>

class SigGen : public QObject
{
  Q_OBJECT

public:
  explicit SigGen(QObject *parent = 0);
  void action(void);

signals:
  void sgAction(int value);
};

#endif // SIGGEN_H

siggen.cpp:

#include "siggen.h"

SigGen::SigGen(QObject *parent) : QObject(parent)
{}

void SigGen::action()
{
  emit sgAction(42);
}
like image 184
fat Avatar answered Sep 28 '22 07:09

fat