How can I use replacedlg.ui in mainwindow.cpp?

47 views Asked by At

I have written a project which includes a mainwindow and a replacedlg.ui. I want to use replacedlg.ui in mainwindow.cpp.

I'd like to write things like ui->button in mainwindow.cpp, but I can't.

Who can help me make this work?

The whole project is here.

1

There are 1 answers

0
thuga On

Don't try to share the ui variable between classes. It is bad design. Instead add methods in your classes which will let you do what you need to do.

In your case where you want to send the text of your line edit from replaceDlg class to your MainWindow class, you should use signals and slots. Here is an example:

#include <QtWidgets>

class MainWindow : public QMainWindow
{
    Q_OBJECT
public:
    MainWindow(QWidget *parent = Q_NULLPTR) : QMainWindow(parent)
    {
        setCentralWidget(&text_edit);
    }
public slots:
    void addText(const QString &text)
    {
        text_edit.append(text);
    }
private:
    QTextEdit text_edit;
};

class Dialog : public QDialog
{
    Q_OBJECT
public:
    Dialog(QWidget *parent = Q_NULLPTR) : QDialog(parent)
    {
        setLayout(new QHBoxLayout);
        QPushButton *send_button = new QPushButton("Send");
        layout()->addWidget(&line_edit);
        layout()->addWidget(send_button);
        connect(send_button, &QPushButton::clicked, this, &Dialog::sendButtonClicked);
    }
signals:
    void sendText(const QString &text);
private slots:
    void sendButtonClicked()
    {
        emit sendText(line_edit.text());
        accept();
    }
private:
    QLineEdit line_edit;
};

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    MainWindow w;
    Dialog d;
    QObject::connect(&d, &Dialog::sendText, &w, &MainWindow::addText);
    w.show();
    d.show();    
    return a.exec();
}

#include "main.moc"