Hi there,

I'm writing some application based on Qt and C++ and I've reached the problem. How to display window via clicking, triggering, etc. I wrote some code:

//----------------------------
// THIS IS IN 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();

private:
    Ui::MainWindow *ui;

private slots:
    void DisplayAuthors();

};

#endif // MAINWINDOW_H
//----------------------------
// THIS IS IN mainwindow.cpp
//----------------------------
#include "mainwindow.h"
#include "authorswindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    connect(ui->actionAutorzy, SIGNAL(triggered()), this, SLOT(DisplayAuthors()));
}

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

void MainWindow::DisplayAuthors()
{
    AuthorsWindow authors;
    authors.show();
}

The AuthorsWindow is simple window with labels and one image (nothing more). As you can see I'm trying to display window from choosing menu item and clicking it. The signal and slot are both working correctly, becouse (this.close();) works on DisplayAuthors(). The point is - window does not apper. What's wrong with my code?

I believe you need a parent QWidget for your new window. And, I also think that your window should be persistent, if you are going to just show() it (as opposed to exec() it). So, I think that the following should work better:

class MainWindow : public QMainWindow
{
    Q_OBJECT
public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();
private:
    Ui::MainWindow ui;
    AuthorsWindow authors;  // NOTICE HERE.
private slots:
    void DisplayAuthors();
};

// ...

MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), 
                                          ui(), authors(this)   // NOTICE HERE.
{
    ui.setupUi(this);
    connect(ui.actionAutorzy, SIGNAL(triggered()), this, SLOT(DisplayAuthors()));
}
MainWindow::~MainWindow() { }
void MainWindow::DisplayAuthors()
{
    authors.show();
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.