如何在Qt中的正确区域(考虑样式表)中绘制文本?

时间:2014-03-19 01:45:34

标签: c++ c qt

我试图在QLabel(子类标签)中删除文本。问题是自定义paintEvent()不尊重样式表设置的变量(尤其是填充/边距)。我该如何解决这个问题?

正如你所看到的,我有一个解决方案,它主要是正确的,但边缘不能正常运作。另一种解决方案远非正常,而是沿着正确的道路前进。我知道我需要用QStyle做一些事来获得该区域的大小,但我不明白。文档真的很混乱。

void Label::paintEvent(QPaintEvent *event){
    if (this->elide == Qt::ElideNone){
        QLabel::paintEvent(event);
        return;
    }

    QPainter p(this);
    QFontMetrics fm(font());
    if (fm.width(text()) > contentsRect().width()) {
        if (1){ //this kind of works...
            QRect rect = this->contentsRect();
            rect.adjust(this->margin(), this->margin(), -this->margin(), -this->margin());
            QString elided_txt = this->fontMetrics().elidedText(text(), this->elide, rect.width(), Qt::TextShowMnemonic); //This is the key line.

            p.drawText(rect(), elided_txt, QTextOption(Qt::AlignVCenter | Qt::AlignLeft));
        } else { //the correct solution should look something like this:


            QStyle *style = this->style();

            QRect rect = style->itemTextRect(fm, this->rect(), Qt::AlignVCenter | Qt::AlignHCenter, true, this->text());

            QString elided_txt = this->fontMetrics().elidedText(text(), this->elide, rect.width(), Qt::TextShowMnemonic); //This is the key line.

            style->drawItemText(&p, this->rect(), Qt::AlignVCenter | Qt::AlignLeft, this->palette(), true, elided_txt);
        }
    } else {
        QLabel::paintEvent(event);
    }
}

0 个答案:

没有答案