简体   繁体   中英

How to create custom layout for widget

I'm trying to create a custom widget in QT that looks something like this: 在此处输入图片说明

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.

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);
[..]

Use this.

QPixmap big(75,65);
big.fill(Qt::red);
QPixmap small(25,15);

QVBoxLayout *box = new QVBoxLayout;

QWidget *window = new QWidget;
QLabel *bigLab = new QLabel;
QLabel *smallLab = new QLabel;
QLabel *textLab = new QLabel("Two");
bigLab->setPixmap(big);
smallLab->setPixmap(small);

QHBoxLayout *hLay = new QHBoxLayout;
hLay->addWidget(bigLab);
hLay->addWidget(textLab);

QHBoxLayout *vLay = new QHBoxLayout;
vLay->addWidget(smallLab,0,Qt::AlignRight);

box->addLayout(hLay);
box->addLayout(vLay);

window->setLayout(box);
window->show();

Result:

在此处输入图片说明

What I normally do is:

  1. Design the layout with Qt Designer/Creator using rich features of layouting.
  2. Set its instances (from code) as the item widget of a list or table widget.

Be careful, If the item count of the list is too large, it will perform very slowly.

PS If you really need the layout coded, just use the code generated by Qt designer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM