Juliano Gomes
Juliano Gomes

Reputation: 77

How correctly to call a function from another file?

OK, let's start again...

I've created an project (Qt Widget Application) with Qt Creator.

My project structure:

When I click on DialogForm pushbutton, I need to call the clear() function from MainWindow

In my code below, my project is running, but, the clear() function does not clear the lineedit.

Do anyone known how can i fix this?

Thank you very much!

dialogform.h

#ifndef DIALOGFORM_H
#define DIALOGFORM_H

#include <QDialog>

namespace Ui {
class DialogForm;
}

class DialogForm : public QDialog
{
    Q_OBJECT

signals:
    void clearMainWindow();

public:
    explicit DialogForm(QWidget *parent = 0);
    ~DialogForm();

private slots:
    void on_pbClearLineEdit_clicked();

private:
    Ui::DialogForm *ui;
};

#endif // DIALOGFORM_H

mainwindow.h

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>

namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();

public slots:
    void clear();

private slots:
    void on_pbCallDialog_clicked();

private:
    Ui::MainWindow *ui;
};

#endif // MAINWINDOW_H

dialogform.cpp

#include "dialogform.h"
#include "ui_dialogform.h"
#include "mainwindow.h"

DialogForm::DialogForm(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::DialogForm)
{
    ui->setupUi(this);
}

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

void DialogForm::on_pbClearLineEdit_clicked()
{
    connect(); // need help here. I'm using Qt 5.6.1
}

main.cpp

#include "mainwindow.h"
#include <QApplication>

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

    return a.exec();
}

mainwindow.cpp

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

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
}

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

void MainWindow::on_pbCallDialog_clicked()
{
    DialogForm *dialogForm = new DialogForm(this);
    dialogForm->show();
}

void MainWindow::clear()
{
    ui->lineEdit->clear();
}

Upvotes: 0

Views: 137

Answers (2)

Juliano Gomes
Juliano Gomes

Reputation: 77

The solution:

DialogForm::DialogForm(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::DialogForm)
{
    ui->setupUi(this);
    connect(ui->pbClearLineEdit, &QPushButton::clicked, static_cast<MainWindow*>(parent), &MainWindow::clear);
}

Upvotes: 0

ilim
ilim

Reputation: 4547

myfunction accesses an attribute of class myfile. Therefore it either needs to be a method of myfile as well, or it could be a friend function of the class myfile. In the latter case, however, you would need to give the relevant instance of myfile to myfunction as an argument. All usages of myfunction would need to be updated in either case.

Upvotes: 1

Related Questions