ldlchina ldlchina - 4 months ago 34
C++ Question

QComboBox: Can we make the entire combobox clickable, not just the dropdown button (arrow) itself?

I want to show a text like "Please select one option" on the combobox, and don't show the text in the list, so I set setEditable to true, then set the text to the lineEdit, but after this, only the dropdown button (arrow) is clickable, how can we make the entire combobox clickable? I'm using the QComboBox as below:

QComboBox* combbox= new QComboBox;
combbox->setEditable(true);
combbox->lineEdit()->setReadOnly(true);
combbox->addItem("Option1");
combbox->addItem("Option2");
combbox->lineEdit()->setText("Please select one option");

Answer

I resolved this problem as below:

class QTComboBoxButton : public QLineEdit
{
    Q_OBJECT
public:
    QTComboBoxButton(QWidget *parent = 0);
    ~QTComboBoxButton();

protected:
    void mousePressEvent(QMouseEvent *);
};

QTComboBoxButton::QTComboBoxButton(QWidget *parent /* = 0 */) :
    QLineEdit(parent)
{
}

QTComboBoxButton::~QTComboBoxButton()
{
}

void QTComboBoxButton::mousePressEvent(QMouseEvent * e)
{
    QComboBox* combo = dynamic_cast<QComboBox*>(parent());
    if(combo)
        combo->showPopup();
}

QComboBox* combbox= new QComboBox;
combbox->setEditable(true);
combbox->setLineEdit(new QTComboBoxButton(combbox));
combbox->lineEdit()->setReadOnly(true);
combbox->addItem("Option1");
combbox->addItem("Option2");
combbox->lineEdit()->setText("Please select one option");