2014-01-22 117 views
0

我目前正在建设一个UI,我做的有3个标签被安排在一个水平布局:在QLabel中隐藏或裁剪重叠的文本?

| textLabel     | valueLabel | unitLabel | 

valueLabelunitLabel是右对齐。 unitLabel有固定宽度,valueLabel的宽度是可变的,并取决于它内部的文本长度。 textLabel左对齐并填充剩余的水平空间直至valueLabel

所以,换句话说,textLabel的宽度不是固定的,而是取决于valueLabel的宽度。

我的问题是:当textLabel内的文本变得太长时,它覆盖了valueLabel

有没有办法隐藏或切断重叠文本?我想到了像CSS中的overflow: hidden属性,你可以设置为<div>或类似的东西。我也尝试使用QLineEdit作为工作区,但似乎没有办法让QLineEdit背景变得透明。我该如何解决这个问题?提前致谢!

+0

我创建了网格/水平布局,并将“水平策略=忽略”添加到最左侧标签的属性。它看起来没有重叠,相反,一旦最左边的标签(textLabel)变得太长,它会隐藏在中间标签(valueLabel)下面。 – wolf9000

回答

1

布局中的小部件始终处于不重叠的状态,所以我只是看不到textLabel可能重叠valueLabel。很有可能您的小部件不受布局管理,即使它们已添加到布局中。也许带标签的布局不是另一个布局的子元素,或者未在容器小部件上设置。

你没有告诉我们什么。一个独立的测试用例应该是很好的。

如果您希望标签通过用“...”结束文本而不是突然切断文本,可以使用以下简化版式。

// 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); 
}