2017-11-30 8 views
3

私は項目に以下の方法を追加するQStandardModelとQComboBoxを持っているのタイトルテキストを設定します。 ユーザーがすべての項目の選択を解除すると、ドロップダウンメニューのテキストが「なし」になります。ユーザーが項目のいくつかを選択すると、「複数」がテキストになります。QComboBoxは関係なく、アイテム

QComboBoxのヘッダーテキストを設定する方法が見つかりませんでした。サブクラス化とそれを自分で行う以外に便利な方法はありませんか?

答えて

1

サブクラス化せずに行うのは便利な方法ではありません。実際、サブクラス化は最も便利な方法です。

QComboBoxモデルを実行して、チェックされているアイテムをチェックすることができたとしても、アイテムがすべて(または部分的に)チェックされたら、コンボボックスに自分自身を更新するよう指示する方法はありません。シグナルや特定の機能はありません。

しかし、QComboBoxのサブクラス化は非常に複雑ではありません。paintEvent()を再実装する必要があります。

//return a list with all the checked indexes 
QModelIndexList MyComboBox::checkedIndexes()const 
{ 
    return model()->match(model()->index(0, 0), Qt::CheckStateRole, Qt::Checked, -1, Qt::MatchRecursive); 
} 

// returns a list with all the unchecked indexes 
QModelIndexList MyComboBox::uncheckedIndexes()const 
{ 
    return model()->match(model()->index(0, 0), Qt::CheckStateRole, Qt::Unchecked, -1, Qt::MatchRecursive); 
} 

//return true if all the items are checked 
bool MyComboBox::allChecked()const 
{ 
    return (uncheckedIndexes().count() == 0); 
} 

//return true if all the items are unchecked 
bool MyComboBox::noneChecked()const 
{ 
    return (checkedIndexes().count() == 0); 
} 

void MyComboBox::paintEvent(QPaintEvent *) 
{ 
    QStylePainter painter(this); 

    // draw the combobox frame, focusrect and selected etc. 
    QStyleOptionComboBox opt; 
    this->initStyleOption(&opt); 

    // all items are checked 
    if (allChecked()) 
     opt.currentText = "All"; 
    // none are checked 
    else if (noneChecked()) 
     opt.currentText = "None"; 
    //some are checked, some are not 
    else 
     opt.currentText = "Multiple"; 

    painter.drawComplexControl(QStyle::CC_ComboBox, opt); 

    // draw the icon and text 
    painter.drawControl(QStyle::CE_ComboBoxLabel, opt); 
} 
関連する問題