要使QLineEdit
和QComboBox
中的文本居中显示,可以在创建这些控件时设置它们的对齐方式。以下是如何修改你的 createEditor
方法以实现文本居中显示:
#include <QLineEdit>
#include <QComboBox>
#include <QPainter>
// 省略其他部分...
QWidget *MyStyledDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
qDebug() << "MyStyledDelegate::createEditor";
if (!index.isValid())
return nullptr;
switch(index.column())
{
default: break;
case 0://触发字符
{
QLineEdit *editor = new QLineEdit(parent);
editor->setFrame(false);
editor->setAlignment(Qt::AlignCenter); // 文本居中
return editor;
}
case 1://匹配模式
{
QComboBox *editor = new QComboBox(parent);
editor->setFrame(false);
editor->setEditable(true); // 如果需要,允许用户输入自定义项
editor->setCurrentText(""); // 设置当前选中的文本为空,以便于输入
const QStringList str_list = index.data(Qt::DisplayRole).toStringList();
// 添加所有选项到下拉框并设置为中心对齐
for (const QString& item : str_list)
editor->addItem(item);
editor->setStyleSheet("QComboBox { text-align: center; }"); // 使用样式表设置文本居中
return editor;
}
case 2://触发命令类型
{
QComboBox *editor = new QComboBox(parent);
editor->setFrame(false);
const QStringList str_list = index.data(Qt::DisplayRole).toStringList();
for (const QString& item : str_list)
editor->addItem(item);
editor->setStyleSheet("QComboBox { text-align: center; }"); // 使用样式表设置文本居中
return editor;
}
case 3://触发配置
{
QComboBox *editor = new QComboBox(parent);
editor->setFrame(false);
const QStringList str_list = index.data(Qt::DisplayRole).toStringList();
for (const QString& item : str_list)
editor->addItem(item);
editor->setStyleSheet("QComboBox { text-align: center; }"); // 使用样式表设置文本居中
return editor;
}
}
return nullptr;
}
修改说明
对于
QLineEdit
:- 使用
editor->setAlignment(Qt::AlignCenter);
来将文本水平居中。
- 使用
对于
QComboBox
:- 添加了样式表来将文本居中:
editor->setStyleSheet("QComboBox { text-align: center; }");
- 此外,如果你希望用户能够手动输入内容,也可以使用
editor->setEditable(true);
来允许编辑。
- 添加了样式表来将文本居中:
这样就能确保每个编辑器中的文本都是居中的效果。
内容由零声教学AI助手提供,问题来源于学员提问