Question

I think i have some troubles getting this right: I have a QMainWindow class. In my programm I want to create other classes e.g. for input handling, computation...

Now first from my mainwindow class i want to send to my fileselector (file handler) class to open a file dialog, thus save the selected files internally. Unfortunately I am having troubles to connect the slots.

main window:

MA_FEX::MA_FEX(QWidget *parent)
    : QMainWindow(parent), fileSelector(this)

{
    ui.setupUi(this);
    //this works:
    fileSelector.openFiles(this); 
    //this doesn't:
    connect(ui.actionOpenFiles, SIGNAL(triggered()), fileSelector, SLOT(openFiles(this)));
}

MA_FEX::~MA_FEX()
{  
}

mainwindow header:

class MA_FEX : public QMainWindow
{
    Q_OBJECT

public:
    MA_FEX(QWidget *parent = 0);
    ~MA_FEX();

private:
    Ui::MA_FEXClass ui;
    FileSelection fileSelector;
};

file coordination class:

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

FileSelection::~FileSelection()
{
}

void FileSelection::openFiles(QWidget *parent){

    QStringList files = QFileDialog::getOpenFileNames(
                         parent,
                         "Select one or more files to open",
                         "c:",
                         "Images (*.csv *.txt )");

}

header:

class FileSelection : public QObject
{
    Q_OBJECT

public:
    FileSelection(QObject *parent);
    ~FileSelection();

public slots:
    void openFiles(QWidget *parent);

private:

};

Am I missing something ? Executing i get Error C2664 on the connect line saying that Parameter 3 'FileSelection' cannot be converted to 'const QObject'.

Was it helpful?

Solution

Look at the declaration of the QObject::connect:

QObject::connect(const QObject * sender, const char * signal,
                 const QObject * receiver, const char * method,
                 Qt::ConnectionType type = Qt::AutoConnection);

It takes pointers, so you need to pass a pointer to fileSelector.

Another problem there is incompatible SIGNAL and SLOT. The slot specification in connect is declaration, so you cannot pass arguments as you did with this. If you use Qt 5 and C++11 you can do that by passing lambda instead of slot specification:

QObject::connect(ui.actionOpenFiles, &QAction::triggered, 
                [this]() { fileSelector.openFiles(this); });

For Qt 4 you need to create wrapping slot in your MA_FEX class which takes no arguments and which will invoke the slot of the fileSelector:

class MA_FEX {
  ...
  Q_SLOT void openFileSelector() { fileSelector.openFiles(this); }
  ...
public:
  MA_FEX(QWidget *parent) : QMainWindow(parent), fileSelector(this) {
    ui.setupUi(this);
    connect(ui.actionOpenFiles, SIGNAL(triggered()), SLOT(openFileSelector()));
  }
  ...
};
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top