How to create custom layout for widget

 ̄綄美尐妖づ 提交于 2019-12-13 06:57:54

问题


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.


回答1:


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



回答2:


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:




回答3:


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.

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



来源:https://stackoverflow.com/questions/26802294/how-to-create-custom-layout-for-widget

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!