Home > other >  Qt: How do I connect a SIGNAL sent from MainWindow to a SLOT on a QDialog?
Qt: How do I connect a SIGNAL sent from MainWindow to a SLOT on a QDialog?

Time:07-16

I have a QFileSystemWatcher that emits a signal called watcher in MainWindow. This works properly in MainWindow. However I need this signal to also update a QDialog window if it is open when the signal is sent.

I am unable to get the signal in main window to active the method in my QDialog class. Any help is appreciated!

MainWindow.cpp:

void MainWindow::on_Open_Display_itemDoubleClicked(QTreeWidgetItem *item, int column)
{
    //gets event index
    size_t i = item->text(6).toInt();

    //executes window
    AddComment *ac = new AddComment;
    ac->set_Data(entries, i);
    
    connect(ac, &QFileSystemWatcher::fileChanged, ac, &AddComment::reset_Data);


    ac->show();
}

AddComment.h:

public slots:
    void reset_Data(Entries &entries);

AddComment.cpp:

void AddComment::reset_Data(Entries &entries)
{
    //my code
}

Edit: I changed MainWindow.cpp to:

void MainWindow::on_Open_Display_itemDoubleClicked(QTreeWidgetItem *item, int column)
{
    //gets event index
    size_t i = item->text(6).toInt();

    //executes window
    AddComment *ac = new AddComment;
    ac->set_Data(entries, i);

    connect(&watcher, SIGNAL(fileChanged(QString)), ac, SLOT(reset_Data(entries)));

    ac->show();
}

I cannot call the connect() in the constructor of MainWindow because I need it to connect to ac which wont be constructed until I double click on my Open_Display ui element.

I also cannot call the connect() in the constructor of the AddComment class because I need to pass an updated &entries from MainWindow into AddComment each time the signal is sent.

CodePudding user response:

There are several issues with your code.

You seem to make this connection when the double click happens. So, Qt is not aware of this connection prior to that.

It is possible that you have not run this codepath as it depends on the double click.

You would need to do this in a codepath that is executed during the initialisation, so presumably in your main window constructor.

Also, your dialog slot expects Entries & which is not something the file system watcher will provide for you.

Another issue is that the signal sender is ac, not actually your file system watcher instance. So, this would not work unless you AddComment is a QFileSystemWatcher subclass mingled with QDialog as you seem to show that later. But do not do this if you are currently doing so. This is not a good idea to mix the two into one subclass.

You need to sort these out before your code makes sense.

CodePudding user response:

I was able to solve my issue. I created a pointer to entries and pass it into my qDilog through a separate function. This eliminates the need for passing &entries and allowed me to place my connection when AddComment is initialized.

  • Related