QCombobox內容居中(包含展示內容,下拉列表)

1.本文達到效果如下:

2.代碼如下

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    resize(600, 400);

    QComboBox* box = new QComboBox (this);
    m_lineeidt = new QLineEdit (box);
    m_lineeidt->setObjectName("lineedit");
    m_lineeidt->setAutoFillBackground(true);
    m_lineeidt->setStyleSheet("QLineEdit#lineedit,QLineEdit#lineedit:disabled{ border: none; font: 13px \"Microsoft YaHei\"; color: black; margin: 0px 20px 0px 1px;background: white;}");
    connect(box, SIGNAL(currentIndexChanged(const QString&)), m_lineeidt, SLOT(setText(const QString&)));
    QHBoxLayout* layoutBox = new QHBoxLayout; layoutBox->setSpacing(0);layoutBox->setMargin(0);
    box->setLayout(layoutBox);
    layoutBox->addWidget(m_lineeidt);
//    box->setLineEdit(m_lineeidt); 屏蔽掉,重新覆蓋一層lineedit,否則點擊內容空白部分,不會彈出combobox的列表框
    auto layout = new QHBoxLayout();
    setLayout(layout);

    layout->addWidget(box);
    QStringList items;
    items << "hello world!" << "aabbccddeeff" << "11223334444" << QString::fromUtf8("你好");
    box->addItems(items);

    m_lineeidt->setReadOnly(true);
    m_lineeidt->setEnabled(false);
    m_lineeidt->setAlignment(Qt::AlignCenter);
    m_lineeidt->installEventFilter(this);

    connect(this, &Widget::lineeditClick, [&box](){
        qDebug() << "Widget::lineeditClick";
    });
}

Widget::~Widget()
{
    delete ui;
}

bool Widget::eventFilter(QObject *watched, QEvent *event)
{
    if(watched == m_lineeidt && event->type() == QEvent::MouseButtonPress){
        auto mEvent = reinterpret_cast<QMouseEvent*>(event);
        if(mEvent->buttons() & Qt::LeftButton){
            emit lineeditClick();
        }
    }

    return __super::eventFilter(watched, event);
}

3.如果需要下拉列表居中,可以採用以下兩個方法

方法一:重載combobox->view->model的data函數,修改 Qt::TextAlignmentRole 統一改爲Qt::AlignCenter

方法二:添加combobox委託 setItemDelegate,重載paint函數,居中繪製文本信息,此方法可以實現自定義繪製信息,ps:


 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章