Qt QComboBox内容居中
Qt-QComboBox内容居中设置
1. 显示内容居中
QComboBox *comboBox = new QComboBox;
QLineEdit *lineEdit = new QLineEdit;
lineEdit->setReadOnly(true);
lineEdit->setAlignment(Qt::AlignCenter);
// 监听lineEdit事件
connect(lineEdit,&QLineEdit::selectionChanged,[=]{
lineEdit->deselect();//防止点击lineEdit内容选中样式
});
connect(box,&QComboBox::currentTextChanged,[=](const QString &text){
for(int i = 0; i < box->count(); i++)
{
if(box->itemText(i) == text)
{
box->setCurrentIndex(i);
break;
}
}
});
comboBox ->setLineEdit(lineEdit);
这样做有个问题:必须点击ComboBox控件的下拉按钮,才可以弹出选择框,因此需要对lineEdit控件的点击事件进行监听,实现点击QComboBox任何位置都可以弹出下拉选择框。
- 具体实现
CQComboBox为继承QComboBox
lineEdit->installEventFilter(this);
bool CQComboBox::eventFilter(QObject *watched, QEvent *event)
{
if(QString(watched->metaObject()->className()) == "QLineEdit")
{
if (event->type() == QEvent::MouseButtonPress
|| event->type() == QEvent::MouseButtonDblClick
|| event->type() == QEvent::TouchBegin)
{
CQComboBox* box = qobject_cast<CQComboBox*>(watched->parent());
if(box && box == this)
{
//m_bShowPopup 重写show和hide 获取显示标记
if(box->isEnabled()&&m_bShowPopup==false)
{
box->showPopup();
}
}
return true;
}
}
return false;
}
2 .下拉菜单内容居中
QStandardItemModel * model = qobject_cast<QStandardItemModel*>(comboBox ->model());
for (int i = 0; i < model->rowCount(); ++i)
{
QStandardItem * item = model->item(i);
item->setTextAlignment(align); //Qt::AlignCenter
item->setSizeHint({ 0, 25});
}