无论项目如何,QComboBox都会设置标题文本

Haf*_*uss 5 c++ qt qt5

我有一个带有QStandardModel的QComboBox,我通过以下方式添加项目:

QStandardItem * item = new QStandardItem();
item->setText("someText");
item->setCheckable(true);

item->setFlags(Qt::ItemIsUserCheckable | Qt::ItemIsEnabled);
item->setData(Qt::Checked, Qt::CheckStateRole);

m_model->appendRow(item);
m_ComboBox->setModel(m_model);
Run Code Online (Sandbox Code Playgroud)

这给了我一个带复选框的组合框,这正是我想要的.现在,当用户取消选择所有项目时,"无"应该是下拉菜单的文本.如果用户选择了一些项目,则"多个"将是文本.

我还没有找到如何设置QComboBox的标题文本的方法.除了子类化和自己做之外没有方便的方法吗?

IAm*_*PLS 6

没有子类化就没有方便的方法来做到这一点。事实上,子类化是最方便的方法。

即使您可以运行 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);
}
Run Code Online (Sandbox Code Playgroud)