ZBLOG

"QComboBox QAbstractItemView::item {" // " height:28px;" // 每一项固定高度 " padding-top:10px;" // 顶部内边距(如果需要) " padding-bottom:10px;" // 底部内边距(如果需要) " ...

QComboBox 的下拉列表中,想要让每个项目(item)横向居中,可以使用 QStyledItemDelegate 来实现。这种情况下,直接使用样式表可能无法达到预期效果,因为 item 的文本居中通常需要在绘制时处理。

但是,你可以尝试设置项目的 alignment 属性,这样在显示时会更容易达到你想要的效果。以下是一些常见的方法:

1. 使用 QStyledItemDelegate

首先,你可以创建一个自定义的代理类,重写 paint 方法来设置文本的对齐方式:

  1. #include <QStyledItemDelegate>
  2. class CenteredItemDelegate : public QStyledItemDelegate {
  3. public:
  4. CenteredItemDelegate(QObject *parent = nullptr) : QStyledItemDelegate(parent) {}
  5. void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const override {
  6. // 设置文本居中
  7. option.displayAlignment = Qt::AlignHCenter | Qt::AlignVCenter;
  8. QStyledItemDelegate::paint(painter, option, index);
  9. }
  10. };

然后,在你的 QComboBox 中应用这个代理:

  1. ui->comboBox->setItemDelegate(new CenteredItemDelegate(ui->comboBox));

2. 使用样式表调整边距(如果不使用自定义代理)

如果只是希望通过样式表简单调整某些方面,可以尝试在样式表里添加 text-align: center;。不过这对于具体的下拉选项可能不起作用,取决于Qt版本和操作系统平台的支持程度。

例如:

  1. QString comboBoxStyle = QString(
  2. "QComboBox {"
  3. " border: 1px solid rgb(102, 138, 222);"
  4. " border-radius: 4px;"
  5. " padding: 5px;"
  6. " background-color: white;"
  7. "}"
  8. // ...之前的代码...
  9. "QComboBox QAbstractItemView {"
  10. " border: 1px solid rgb(102, 138, 222);"
  11. " background-color: white;"
  12. " selection-background-color: #f5f7fa;"
  13. " selection-color: #409eff;"
  14. "}"
  15. "QComboBox QAbstractItemView::item {"
  16. " height:28px;"
  17. " padding-top:10px;"
  18. " padding-bottom:10px;"
  19. // 尝试使用 text-align 来实现水平居中
  20. " text-align:center;"
  21. "}");
  22. // 设置组合的样式表到 comboBox 上
  23. ui->comboBox->setStyleSheet(comboBoxStyle);

小结

最可靠的方法是创建并应用一个自定义的 QStyledItemDelegate 类来控制项内容的绘制。如果有其他特定需求或上下文,请随时告知!


内容由零声教学AI助手提供,问题来源于学员提问

本站部分文章来源于网络,版权归原作者所有,如有侵权请联系站长删除。
转载请注明出处:https://golang.0voice.com/?id=22192

分享:
扫描分享到社交APP
上一篇
下一篇
发表列表
游客 游客
此处应有掌声~
评论列表

还没有评论,快来说点什么吧~

联系我们

在线咨询: 点击这里给我发消息

微信号:3007537140

上班时间: 10:30-22:30

关注我们
x

注册

已经有帐号?