【QT】 QComboBox实现可下拉可编辑

1.设置可编辑模式

comboBox->setEditable(true);

2.设置可编辑模式后,可以获取comboBox里QLineEdit

指向comboBox对应的QLineEdit,注意非可编辑模式,该对象为NULL

comboBox->lineEdit() 

3.clearEditText可以被用来清除用于显示的字符串而不改变ComboBox的内容。

comboBox->clearEditText();

4.密保问题,一般最后一项都是自定义,此处可以配合QLineEdit代理实现
 

QLineEdit *lineEditQ1 = new QLineEdit (this);

lineEditQ1->setReadOnly(true);

lineEditQ1->setPlaceholderText("Customized Question");

comboBox->setLineEdit(lineEditQ1);

connect(ui->comboBox_question1, SIGNAL(currentIndexChanged(int)), this, SLOT(slotChangeQuestion(int)));

void xxx::slotChangeQuestion(int index)
{
	CustomComboBox *senderComBox = static_cast<CustomComboBox *>(sender());
	if (index == SQA_CUSTOMIZED_NO)
	{
		senderComBox->lineEdit()->setReadOnly(false);
		senderComBox->lineEdit()->clear();
	}
	else
	{
		comboBox->lineEdit()->setReadOnly(true);
	}
}

5.在4的基础上实现,会出现在QLineEdit设置为只读模式时,点击后下拉选项闪一下又没掉的问题,需要重写combobox的hidePopup函数

connect(lineEditQ1,SIGNAL(sigClicked()),this,SLOT(virtualKeyboardUpdatePosition()));


void UserSetting::virtualKeyboardUpdatePosition()
{
	CustomLineEdit *senderComBox = static_cast<CustomLineEdit *>(sender());
	if (senderComBox == this->lineEditQ1)
	{
		if (!this->lineEditQ1->isReadOnly())
		{
			;//edit enabled
		}
		else
		{
			comboBox->setShow();
		}
	}
	
}


void hidePopup() override;
void setShow();
bool _editMode;


void CustomComboBox::hidePopup()
{
	if (_editMode)
	{
		_editMode = false;
	}
	else
	{
    	QComboBox::hidePopup();
	}
}

void CustomComboBox::setShow()
{
	_editMode = true;
	this->showPopup();
}

6.获取当前combobox内容

comboBox->currentText().trimmed()

猜你喜欢

转载自blog.csdn.net/y7u8t6/article/details/83152142