ZBLOG

#include "MyStyledDelegate.h" #include #include #include #pragma execution_character_set("utf-8") MyStyledDelegate::MyStyledDelegate(QObject *parent) : QStyledItemDelegate(parent) { } void My...

要使QLineEditQComboBox中的文本居中显示,可以在创建这些控件时设置它们的对齐方式。以下是如何修改你的 createEditor 方法以实现文本居中显示:

  1. #include <QLineEdit>
  2. #include <QComboBox>
  3. #include <QPainter>
  4. // 省略其他部分...
  5. QWidget *MyStyledDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const
  6. {
  7. qDebug() << "MyStyledDelegate::createEditor";
  8. if (!index.isValid())
  9. return nullptr;
  10. switch(index.column())
  11. {
  12. default: break;
  13. case 0://触发字符
  14. {
  15. QLineEdit *editor = new QLineEdit(parent);
  16. editor->setFrame(false);
  17. editor->setAlignment(Qt::AlignCenter); // 文本居中
  18. return editor;
  19. }
  20. case 1://匹配模式
  21. {
  22. QComboBox *editor = new QComboBox(parent);
  23. editor->setFrame(false);
  24. editor->setEditable(true); // 如果需要,允许用户输入自定义项
  25. editor->setCurrentText(""); // 设置当前选中的文本为空,以便于输入
  26. const QStringList str_list = index.data(Qt::DisplayRole).toStringList();
  27. // 添加所有选项到下拉框并设置为中心对齐
  28. for (const QString& item : str_list)
  29. editor->addItem(item);
  30. editor->setStyleSheet("QComboBox { text-align: center; }"); // 使用样式表设置文本居中
  31. return editor;
  32. }
  33. case 2://触发命令类型
  34. {
  35. QComboBox *editor = new QComboBox(parent);
  36. editor->setFrame(false);
  37. const QStringList str_list = index.data(Qt::DisplayRole).toStringList();
  38. for (const QString& item : str_list)
  39. editor->addItem(item);
  40. editor->setStyleSheet("QComboBox { text-align: center; }"); // 使用样式表设置文本居中
  41. return editor;
  42. }
  43. case 3://触发配置
  44. {
  45. QComboBox *editor = new QComboBox(parent);
  46. editor->setFrame(false);
  47. const QStringList str_list = index.data(Qt::DisplayRole).toStringList();
  48. for (const QString& item : str_list)
  49. editor->addItem(item);
  50. editor->setStyleSheet("QComboBox { text-align: center; }"); // 使用样式表设置文本居中
  51. return editor;
  52. }
  53. }
  54. return nullptr;
  55. }

修改说明

  1. 对于 QLineEdit:

    • 使用 editor->setAlignment(Qt::AlignCenter); 来将文本水平居中。
  2. 对于 QComboBox:

    • 添加了样式表来将文本居中:editor->setStyleSheet("QComboBox { text-align: center; }");
    • 此外,如果你希望用户能够手动输入内容,也可以使用 editor->setEditable(true); 来允许编辑。

这样就能确保每个编辑器中的文本都是居中的效果。


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

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

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

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

联系我们

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

微信号:3007537140

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

关注我们
x

注册

已经有帐号?