1. 程式人生 > >【QT】 QComboBox實現可下拉可編輯

【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()