美文网首页
QLabel中加入其他控件

QLabel中加入其他控件

作者: BrokenRainK | 来源:发表于2021-02-02 12:05 被阅读0次

今天有个需求,需要做一个类似QQ在线离线显示的图标,如下图


在线

本以为可以分分钟搞定,结果发现在UI设计界面无法将其他控件拖入到QLabel中。
特此记录一下解决方案,希望可以帮助到其他和我一样遇到此问题的同学。

方法一

在文本编辑器中修改*.ui文件

  • 在UI设计器拖入两个QLabel
  • 右键*.ui文件->用...打开->普通文本编辑器,直接修改ui文件

    将图中选中部分剪切到另一个label中

如下所示:

<widget class="QWidget" name="centralWidget">
   <widget class="QLabel" name="label">
    <property name="geometry">
     <rect>
      <x>50</x>
      <y>60</y>
      <width>50</width>
      <height>50</height>
     </rect>
    </property>
    <property name="text">
     <string>TextLabel</string>
    </property>
    <widget class="QLabel" name="label_2">
     <property name="geometry">
      <rect>
       <x>140</x>
       <y>90</y>
       <width>16</width>
       <height>16</height>
      </rect>
     </property>
     <property name="text">
      <string>TextLabel</string>
     </property>
    </widget>
   </widget>
  </widget>
  • 在UI设计器中打开ui文件,你会发现其中一个label已经放入另一个label中了


    image.png
  • 最后只需在UI设计器中根据自己的需求修改大小和位置即可

方法二

在代码中实现控件的布局

QLabel *pHead = new QLabel(this);
QLabel *pStatus = new QLabel();
QVBoxLayout *pVBLayout = new QVBoxLayout();
QHBoxLayout *pHBLayout = new QHBoxLayout();

pHBLayout->addStretch();                //添加可伸缩项
pHBLayout->addWidget(pStatus);
pHBLayout->setMargin(0);

pVBLayout->addStretch();
pVBLayout->addLayout(pHBLayout);
pVBLayout->setMargin(0);
pHead->setLayout(pVBLayout);

pHead->setFixedSize(50, 50);          //头像大小可根据实际需求修改
pStatus->setFixedSize(16, 16);        //状态大小可根据实际需求修改
pHead->setStyleSheet("background: red; border-radius: 8px;");    //圆角大小可根据实际需求修改
pStatus->setStyleSheet("background: blue; border-radius: 8px;"); //圆角大小可根据实际需求修改
效果图如下: 效果图

\color{red}{注:其他不能在UI设计器中拖入的控件同理,如QPushButton等。}

相关文章

网友评论

      本文标题:QLabel中加入其他控件

      本文链接:https://www.haomeiwen.com/subject/rkaetltx.html