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});
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值