我正在尝试删除QLabel(子类为Label)中的文本。问题在于自定义项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);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1123 次 |
| 最近记录: |