Как отправить сообщение из дочернего виджета в родительское окно в Qt? - PullRequest
0 голосов
/ 13 марта 2020

Как отправить сообщение из дочернего виджета в родительское окно в qt? Я попытался отправить сигнал из дочернего виджета в родительское окно в qt. Когда я вызываю функцию test в subwidget. cpp, сигнал отправляется, но слот главного окна не выполняется. Как я могу отправить сообщение?

mainwindow.h

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include <QStackedWidget>
#include <QPushButton>
#include <QProcess>
#include <QDebug>
#include <subwidget.h>

QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACE

class MainWindow : public QMainWindow
{
   Q_OBJECT

   public:
       MainWindow(QWidget *parent = nullptr);
       ~MainWindow();
       void check_adb_exists();

   private:
       Ui::MainWindow *ui;
       QStackedWidget *stack;
       QPushButton *start_btn;
       SubWidget *f2;

   private slots:
       void StartApplication();
       void ReceiveCustomMessage(const QString &msg);

};
#endif // MAINWINDOW_H

subwidget.h

#define SUBWIDGET_H

#include <QWidget>

namespace Ui {
class SubWidget;
}

class SubWidget : public QWidget
{
    Q_OBJECT

public:
    explicit SubWidget(QWidget *parent);
    ~SubWidget();
    void test();

private:
    Ui::SubWidget *ui;

signals:
    void SendCustomMessage(const QString& msg);
};

#endif // SUBWIDGET_H

mainwindow. cpp

#include "mainwindow.h"
#include "ui_mainwindow.h"
// #include <formcustomnew.h>
#include <subwidget.h>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    stack = MainWindow::findChild<QStackedWidget *>("stackedWidget");
    start_btn = MainWindow::findChild<QPushButton *>("start_btn");
    stack->setCurrentIndex(0);
    connect(start_btn,SIGNAL(released()),this,SLOT(StartApplication()));
    f2 = new SubWidget(this);
    //connect(f2,SIGNAL(SendCustomMessage(QString)),this,SLOT(ReceiveCustomMessage(QString)));
    //f2->test();
    //auto f1 = new FormCustomNew(this);
    //connect(f1,SIGNAL(sendMessageNewMessage(QString)),this,SLOT(receiveMessage(QString)));
    //f1->test();
}

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

void MainWindow::StartApplication(){
    //check_adb_exists();
    f2->test();
}

void MainWindow::ReceiveCustomMessage(const QString &msg){
    qDebug("Recieved message from child");
    qDebug("Message: " + msg.toLatin1());
}

void MainWindow::check_adb_exists(){
    QProcess *p = new QProcess();
    connect(p,&QProcess::readyReadStandardOutput,[&](){
        auto data = p->readAllStandardOutput();
        qDebug("Stdout: " + data);
    });
    connect(p,&QProcess::readyReadStandardError,[&](){
        auto data = p->readAllStandardError();
        qDebug("Error: " + data);
        if(data.toStdString().compare("File Not Found")){
            qDebug("File Not Found is the error");
        }
    });
    QStringList args;
    args << "/c dir C:\\Users\\%USERNAME%\\AppData\\Local\\Android\\Sdk";
    p->setArguments(args);
    p->setProgram("C:\\Windows\\System32\\cmd.exe");
    p->start();
}

подвиджет. cpp

#include "subwidget.h"
#include "ui_subwidget.h"

SubWidget::SubWidget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::SubWidget)
{
    ui->setupUi(this);
    qDebug("parent: " + parent->objectName().toLatin1());
    connect(this,SIGNAL(SendCustomMessage(QString)),parent,SLOT(ReceiveCustomMessage(QString)));
}

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

void SubWidget::test(){
    emit SendCustomMessage("trial message");
}

void SubWidget::SendCustomMessage(const QString &msg){
    qDebug("Sending Message: " + msg.toLatin1());
}

1 Ответ

0 голосов
/ 13 марта 2020

Сигналы не должны быть определены в Qt.

Из вики Qt на Сигналы и слоты:

Сигналы автоматически генерируются модулем mo c и не должны быть реализованы в. cpp файле

Удалите вашу реализацию, и это должно работать. Однако вы не должны связывать сигнал в пределах subclass, так как это уменьшает инкапсуляцию и возможность повторного использования (у родителя должен быть слот ReceiveCustomMessage(QString)). Вместо этого свяжите это снаружи, как у вас в закомментированном коде.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...