Search code examples
c++qtqwidget

How to create custom layout for widget


I'm trying to create a custom widget in QT that looks something like this: enter image description here

The red squares will be displaying an image/icon. How can I achieve this layout through coding the widget? I will need to create many of those widgets with the same layout but different values in their labels. Ideally, I will display those widgets as a list with a scrollbar in my mainwindow. But right now I'm struggling to just create the layout for those widgets through code. Any help is much appreciated.


Solution

  • You need to split you design on to separate segments. Each segment can be either a separate sub layout or a widget. In you example, I see the following segments:

    • Large red icon,
    • Two labels: TextLabel and 06-November-2014...
    • Two labels make a vertical box layout,
    • Vertical box layout and large red icon make a horizontal box layout,
    • Small red rectangle makes a separate layout,
    • All layouts make a main layout.

    Now lets code this composition:

    QLabel *largeRed = new QLabel(this); // Should set an image for this label
    QLabel *lbl1 = new QLabel("06-November-2014...", this);
    QLabel *lbl2 = new QLabel("TextLabel", this);
    
    QVBoxLayout *vLayout = new QVBoxLayout;
    vLayout->addWidget(lbl1);
    vLayout->addWidget(lbl2);
    vLayout->addStretch();
    
    QHBoxLayout *hLayout = new QHBoxLayout;
    hLayout->addWidget(largeRed);
    hLayout->addLayout(vLayout);
    
    QLabel *smallRed = new QLabel(this); // Should set an image for this label
    QHBoxLayout *hLayout2 = new QHBoxLayout;
    hLayout2->addWidget(smallRed, 0, Qt::AlignRight);
    
    QVBoxLayout *mainLayout = new QVBoxLayout(this);
    mainLayout->addLayout(hLayout);
    mainLayout->addLayout(hLayout2);
    [..]