Hide or crop overlapping text in QLabel?

前端 未结 1 612
走了就别回头了
走了就别回头了 2021-01-26 04:31

I\'m currently building a UI where I do have 3 labels that are arranged in a horizontal layout:

| textLabel                    | valueLabel | unitLabel |
         


        
相关标签:
1条回答
  • 2021-01-26 05:03

    Widgets in a layout are always managed not to overlap, so I just see no way that the textLabel could overlap valueLabel. Most likely your widgets are not managed by the layout, even if they were added to the layout. Perhaps the layout with labels is not a child of another layout, or is not set on a container widget.

    You're not telling us something. A self-contained test case would be good to have.

    If you want a label to elide the text by finishing it with "..." instead of abruptly cutting it off, the following elided style can be used.

    // Usage:
    /*
       QApplication app;
       app.setStyle(new ElidedStyle);
       ...
       QWidget * w = new QLabel("Hello World!");
       w->setProperty("elidedItemText", true); 
    */
    
    // Interface
    
    class ElidedStyle : public QProxyStyle
    {
    public:
       static QString elidedText(const QString & text, QPainter * painter, const QRect & rect);
       virtual void drawItemText(
          QPainter * painter, const QRect & rect, int flags, const QPalette & pal, 
          bool enabled, const QString & text, QPalette::ColorRole textRole = QPalette::NoRole) const Q_DECL_OVERRIDE;
    };
    
    // Implementation
    
    QString ElidedStyle::elidedText(const QString & text, QPainter * painter, const QRect & rect)
    {
       QWidget * widget = dynamic_cast<QWidget*>(painter->device());
       if (widget && widget->property("elidedItemText").toBool()) {
          QFontMetrics fm(painter->font());
          return fm.elidedText(text, Qt::ElideMiddle, rect.width());
       }
       return text;
    }
    
    void ElidedStyle::drawItemText(
       QPainter * painter, const QRect & rect, int flags, const QPalette & pal,
       bool enabled, const QString & text, QPalette::ColorRole textRole) const
    {
       QProxyStyle::drawItemText(painter, rect, flags, pal, enabled, elidedText(text, painter, rect), textRole);
    }
    
    0 讨论(0)
提交回复
热议问题