Slot doesn't work in new window
I create a main window, which opens a new window on a button click. That works fine, but the new window's button doesn't respond to clicks. I have included Q_OBJECT in the class declaration. The code is as follows:
main.cpp:
Code:
#include <QtGui/QApplication>
#include "mainwindow.h"
#include "AnotherWindow.h"
int main(int argc, char *argv[])
{
MainWindow w;
w.show();
return a.exec();
}
mainwindow.h:
Code:
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QObject>
#include <QWidget>
{
Q_OBJECT
public:
explicit MainWindow
(QWidget *parent
= 0);
~MainWindow();
private slots:
void TestFunction();
};
#endif // MAINWINDOW_H
mainwindow.cpp:
Code:
#include <QtGui>
#include "mainwindow.h"
#include "AnotherWindow.h"
MainWindow
::MainWindow(QWidget *parent
){
layout->addWidget(pb);
this->setLayout(layout);
connect(pb, SIGNAL( clicked() ), this, SLOT( TestFunction() ));
}
void MainWindow::TestFunction()
{
qDebug("This is a test");
AnotherWindow aw;
}
MainWindow::~MainWindow()
{
}
AnotherWindow.h:
Code:
#ifndef ANOTHERWINDOW_H
#define ANOTHERWINDOW_H
#include <QObject>
#include <QWidget>
class AnotherWindow
: public QWidget{
Q_OBJECT
public:
AnotherWindow
(QWidget* parent
= 0);
private slots:
void AnotherTest();
}
;
#endif // ANOTHERWINDOW_H
AnotherWindow.cpp:
Code:
#include <QtGui>
#include <QDebug>
#include "AnotherWindow.h"
AnotherWindow
::AnotherWindow(QWidget* parent
){
anotherLayout->addWidget(pushy);
connect(pushy, SIGNAL(clicked()), this, SLOT(AnotherTest()));
window->setLayout(anotherLayout);
window->show();
}
void AnotherWindow::AnotherTest()
{
qDebug("Why isn't this code hit?");
}
Re: Slot doesn't work in new window
Here's one (and possibly the) problem:
Code:
void MainWindow::TestFunction()
{
qDebug("This is a test");
AnotherWindow aw;
}
Here you instantiate an AnotherWindow on the stack. What happens here is that the window you create gets destroyed immediately after construction. The push button's clicked() signal automagically detects that the connection was broken, hence there is no activity. The widget you see is the widget created in the AnotherWindow constructor (which is superfluous, btw).
Better code would probably be:
Code:
void MainWindow::TestFunction()
{
qDebug("This is a test");
AnotherWindow *aw = new AnotherWindow(this);
aw->show();
}
Code:
AnotherWindow
::AnotherWindow(QWidget* parent
){
anotherLayout->addWidget(pushy);
connect(pushy, SIGNAL(clicked()), this, SLOT(AnotherTest()));
setLayout(anotherLayout);
}
Hope this helps.
On an unrelated note, you don't need to explicitly include QObject before you include QWidget. QWidget is a QObject and the dependency implications are handled for you by the compiler. It won't make much of a difference during compiling, it is more of a style issue.
Re: Slot doesn't work in new window
Perfect, thanks for your help!