ZBLOG

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

要使QLineEditQComboBox中的文本居中显示,可以在创建这些控件时设置它们的对齐方式。以下是如何修改你的 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;
}

修改说明

  1. 对于 QLineEdit:

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

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

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


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

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

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

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

联系我们

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

微信号:3007537140

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

关注我们
x

注册

已经有帐号?