PDA

View Full Version : Composite Widget Tutorial



tescrin
10th August 2012, 21:33
In QWidget (documentation) it talks about building composite widgets and references a page that's supposed to have a tutorial on how to do it; though i couldn't find it.

Could someone point me in the direction of a thread or tutorial on (or explain) how to:
-Turn a qwidget into a container (I believe it is by default)
-Have it "contain" another widget

Again, I search the reference it gave, but it didn't seem to contain anything on containers/composite widgets. To clarify, I know how to do it in designer; I need to figure out how to do it.


I looked at the ui_myclass.h files to get an idea; it seems that it's enough to just say this during initialization?:

myContainerClass foo = new myContainterClass(ContainedClassName);

Zlatomir
11th August 2012, 03:55
The simplest way is just to: create a QWidget, create a QLayout with that widget as parent and add other widgets to the layout:


QWidget w;
//create a layout with parent
QVBoxLayout *layout = new QVBoxLayout(&w);
//widgets that will be contained in QWidget
QLabel* label1 = new QLabel("Label 1");
QLabel* label2 = new QLabel("Label 2");
layout->addWidget(label1); //add contained widgets to layout
layout->addWidget(label2);
w.show(); //show the widget

Or another way is to derive a class from QWidget and contain the widgets into that class, this creates a better "encapsulated widget" that can be reused easier.


//MyWidget.h file
#ifndef MYWIDGET_H
#define MYWIDGET_H
#include <QWidget>

//forward declarations
class QVBoxLayout;
class QHBoxLayout;
class QLabel;
class QPushButton;

class MyWidget : public QWidget //inherit from QWidget
{
Q_OBJECT
public:
MyWidget(QWidget* parent = 0); //don't forget to pass the parent

private:
//contained widgets:
QVBoxLayout *mainLayout;
QHBoxLayout *anotherLayout;
QLabel *firstLabel;
QLabel *secondLabel;
QPushButton *firstButton;
QPushButton *secondButton;
signals:
//MyWidget's signals....
public slots:
//MyWidget's slots example:
// void firstButtonClicked();
//...
};
#endif // MYWIDGET_H

And in the constructor you initialize the pointers and add them to the layouts:


#include "mywidget.h"
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QLabel>
#include <QPushButton>

MyWidget::MyWidget(QWidget* parent) : QWidget(parent)
{
mainLayout = new QVBoxLayout(this);
anotherLayout = new QHBoxLayout();

firstLabel = new QLabel("first label");
secondLabel = new QLabel("second label");
firstButton = new QPushButton("Fist button");
secondButton = new QPushButton("Second Button");

mainLayout->addWidget(firstLabel);
mainLayout->addWidget(firstButton);
mainLayout->addLayout(anotherLayout);
anotherLayout->addWidget(secondLabel);
anotherLayout->addWidget(secondButton);
}