如何在不可编辑的情况下对齐QComboBox中的下拉项文本



不清楚如何对齐QComboBox下拉/弹出菜单的项目:

  • QComboBox或其子QAbstractItemView上的QSS中使用text-align: left;没有任何作用
  • QComboBox文档中没有提及对齐
  • SO/其他论坛上存在许多类似的问题,但没有令人满意的答案

在问题5.15.2和6.2.1中测试:

// class CustomComboBox : public QComboBox {...};
void CustomComboBox::setDropdownItemAlignment(Qt::Alignment alignment)
{
for (int i = 0; i < count(); i++) {
setItemData(i, QVariant(alignment), Qt::TextAlignmentRole);
}
}

使用

myComboBox->setDropdownItemAlignment(Qt::AlignLeft | Qt::AlignVCenter);

我还没有测试过的另一种可能性是将model()强制转换为QStandardItemModel*,对其行进行迭代并使用setTextAlignment。(未经测试的(草图如下:

// (in a combo box subclass method)
auto stdModel = dynamic_cast<QStandardItemModel*>(model());
for (int i = 0; i < count(); i++) {
stdModel->item(i)->setTextAlignment(Qt::AlignLeft);
}

最新更新