Pages

A simple QMainWindow subclass

In Qt's world, an application main window is a class derived from QMainWindow. I reckon it is usually better to create it through Qt Designer, since even a minimal main window should provide a number of widgets, and it is not much fun take care programmatically of all the details.

In any case, it is possible to do it just using C++, and we are about to show it now, creating a very rough main window.

Here is the include file:

#ifndef WINMAIN_H
#define WINMAIN_H

#include <QMainWindow>

class QCloseEvent;

class WinMain : public QMainWindow
{
Q_OBJECT
public:
explicit WinMain(QWidget* parent = 0);

private:
void closeEvent(QCloseEvent* event); // 1.
bool okToContinue(); // 2.
};
#endif // WINMAIN_H

1. this virtual function defined in QMainWindow allows us to say a last word before the application close. Here we'll just ask the user if he really wants to leave.
2. here we'll display a message box asking the required confirmation.

Let's see the implementation:

#include "WinMain.h"
#include <QtGui/QtGui>

WinMain::WinMain(QWidget* parent) : QMainWindow(parent)
{
setWindowTitle("My Title");
}

void WinMain::closeEvent(QCloseEvent* event) // 1.
{
if(okToContinue())
event->accept();
else
event->ignore();
}

bool WinMain::okToContinue()
{ // 2.
int res = QMessageBox::warning(this, windowTitle(), "Are you pretty sure?",
QMessageBox::Yes | QMessageBox::No);
if(res == QMessageBox::No)
return false;
return true;
}

1. the point of closeEvent() is that we can set the "accepted" member of the passed event to false, that is, we can signal that we don't actually want the closing of the application to be performed. To do that we call the ignore() method on the event itself. It is not strictly a necessity to call accept() otherwise, since by default an event is accepted.
2. we create a warning message box owned by this window, with as title the same one of this window, asking a confirmation, and offering two options: yes or no.

The main is:

#include <QApplication>
#include "WinMain.h"

int main(int argc, char** argv)
{
QApplication app(argc, argv);

WinMain wm;
wm.show();

return app.exec();
}


I wrote this post while reading "C++ GUI Programming with Qt 4, Second Edition" by Jasmin Blanchette and Mark Summerfield.

No comments:

Post a Comment