2016-12-28 14 views
1

QComboBoxです。QComboBox選択した商品にテキストが表示されません

enter image description here

currentText()は、ウィジェットの長すぎる場合、私は省略記号を表示したいです。このよう

:だから

enter image description here

これはflawlessyに取り組んでいる
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); 
} 

。 問題は、左右の境界からの距離をハードコーディングしているため、コメントの間のコードです。それは私をうんざらさせる。そのコードなし

結果は次のとおりです。

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が有効です。

一般に、すべてのコンボボックスでテキストを消去する場合は、を実装し、QStyle::CE_ComboBoxLabelにはMyStyle::drawControlを上書きすることを検討する必要があります。

+0

提案していただきありがとうございます。しばらくするとすぐに、私があなたの提案したものを調査しようとします! –

+0

それは完璧に動作します!ありがとうございました! –

関連する問題