Qt for beginners Exercise 1 answer

From Qt Wiki
Revision as of 16:26, 5 March 2015 by AutoSpider (talk | contribs) (Convert ExpressionEngine section headers)
Jump to navigation Jump to search
This article may require cleanup to meet the Qt Wiki's quality standards. Reason: Auto-imported from ExpressionEngine.
Please improve this article if you can. Remove the {{cleanup}} tag and add this page to Updated pages list after it's clean.

[toc align_right="yes" depth="3"]

Qt for beginners — Exercise 1 : basis (Answer)

<<< Exercise 1 : basis | Summary | Exercise 2 >>>

Widgets

Since this application seems to be quite complicated, we have chosen to split into several files :

main.cpp

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

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

Window window;
 window.show();

return app.exec();
}

window.h

#ifndef WINDOW_H
#define WINDOW_H

#include <QWidget>

class QPushButton;
class QRadioButton;
class Window : public QWidget
{
public:
 explicit Window(QWidget *parent = 0);
private:
 QRadioButton *m_chickenButton;
 QRadioButton *m_sandwichButton;
 QRadioButton *m_soupButton;

QPushButton *m_selectButton;
};

#endif // WINDOW_H

window.cpp

#include "window.h"

#include <QRadioButton>
#include <QPushButton>
#include <QButtonGroup>

Window::Window(QWidget *parent) :
 QWidget(parent)
{
 // Set size of the window
 setFixedSize(200, 150);

// Create and position the button
 m_chickenButton = new QRadioButton("Roasted chicken", this);
 m_chickenButton->setGeometry(10, 10, 180, 30);

m_sandwichButton = new QRadioButton("Sandwich", this);
 m_sandwichButton->setGeometry(10, 40, 180, 30);

m_soupButton = new QRadioButton("Soup", this);
 m_soupButton->setGeometry(10, 70, 180, 30);

m_selectButton = new QPushButton("Select this menu", this);
 m_selectButton->setGeometry(10, 110, 180, 30);

QButtonGroup '''group = new QButtonGroup(this);
 group->addButton(m_chickenButton);
 group->addButton(m_sandwichButton);
 group->addButton(m_soupButton);
}

You can also remove the buttons from the attributes list and put the inside the constructor.


Signals and slots

#include <QApplication>
#include <QPushButton>

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

QWidget window;
 window.setFixedSize(100, 80);

QPushButton *buttonInfo = new QPushButton("Info", &amp;window);
 buttonInfo->setGeometry(10, 10, 80, 30);

QPushButton *buttonQuit = new QPushButton("Quit", &amp;window);
 buttonQuit->setGeometry(10, 40, 80, 30);

window.show();

// Connections
 // Connecting the button associated to info to the "aboutQt" slot of QApplication
 QObject::connect(buttonInfo, SIGNAL (clicked()), &amp;app, SLOT (aboutQt()));

// Connecting the button associated to close to the "quit" slot of QApplication
 QObject::connect(buttonQuit, SIGNAL (clicked()), &amp;app, SLOT (quit()));

return app.exec();
}