2016-12-28 420 views
1

因此,我有一個QComboBoxQComboBox消除選定項目上的文字

enter image description here

如果currentText()過長小部件,然後我要顯示一個省略號。

像這樣:

enter image description here

所以:

void MyComboBox::paintEvent(QPaintEvent *) 
{ 
     QStylePainter painter(this); 
     QStyleOptionComboBox opt; 
     initStyleOption(&opt); 
     painter.drawComplexControl(QStyle::CC_ComboBox, opt); 

     QRect rect = this->rect(); 
     //this is not ideal 
     rect.setLeft(rect.left() + 7); 
     rect.setRight(rect.width() - 15); 
     // 

     QTextOption option; 
     option.setAlignment(Qt::AlignVCenter); 

     QFontMetrics fontMetric(painter.font()); 
     const QString elidedText = QAbstractItemDelegate::elidedText(fontMetric, rect.width(), Qt::ElideRight, this->currentText()); 
     painter.drawText(rect, elidedText, option); 
} 

這是工作flawlessy。 問題是評論之間的代碼,因爲我硬編碼從左邊界和右邊界的距離。這讓我感到害怕。

無代碼的結果是:

enter image description here

有誰知道要做到這一點,沒有硬編碼更一般的方法是什麼? 謝謝

回答

1

在哪裏應該繪製文本完全取決於使用的風格。您可以通過QStyle::subControlRect獲取有關子元素定位的信息。與組合框文本最匹配的子控件似乎是QStyle::SC_ComboBoxEditField,但如果該項目有圖標,則需要考慮這一點。如果項目沒有圖標,你可以用

QRect textRect = style()->subControlRect(QStyle::CC_ComboBox, &opt, QStyle::SC_ComboBoxEditField, this); 
    QFontMetrics fontMetric(painter.font()); 
    const QString elidedText = QAbstractItemDelegate::elidedText(fontMetric, textRect.width(), Qt::ElideRight, this->currentText()); 
    opt.currentText = elidedText; 
    painter.drawControl(QStyle::CE_ComboBoxLabel, opt); 

去你可能想看看如何如QFusionStyle::drawControl適用於細節。

一般來說,如果您希望所有組合框都可以忽略文本,則應考慮實施您自己的QProxyStyle,並且只爲QStyle::CE_ComboBoxLabel覆蓋MyStyle::drawControl

+0

謝謝你的建議..只要我有一段時間我會嘗試調查你的建議! –

+0

它完美無瑕!謝謝! –

相關問題