Reputation: 301
I created an editable QCombobox storing the last inputs by:
QComboBox* input = new QComboBox();
input->setEditable(true);
input->completer()->setCompletionMode(QCompleter::PopupCompletion);
input->setMaxCount(5);
Now I got 2 issues:
I want to limit the size of the dropdown-menu to the last 5 input-strings.
These 5 old inputs shall all be displayed under the editable line on the top. Currently, the old inputs hide the editable line.
For the first aspect, calling ’setMaxCount(5)’ makes the QComboBox display the first 5 items inserted but I want it to display the last 5 items.
For the second aspect, I somehow need to change the style as I think. So changing sth. like these parameters:
setStyleSheet("QComboBox::drop-down {\
subcontrol-origin: padding;\
subcontrol-position: bottom right;\
}");
But I got no idea which parameters here to change s.t. only the last 5 entries are all shown under the input-line of the QComboBox.
EDIT
Here are two pictures of how the dropdown-menu appears. I entered 5 entries as you can see but the edit-line gets hiden by the popup:
In the 2nd picture, the edit-line is right behind the marked entry "5".
Upvotes: 3
Views: 2948
Reputation: 2418
In order to only keep the last 5 items you can start by listening for your QComboBox
's QLineEdit
signal editingFinished()
. When the signal is emitted, you can check the item count and remove the oldest item if the count is 6.
To reposition the drop down menu, you have to subclass QComboBox
and reimplement the showPopup()
method. From there you can specify how to move the popup menu.
Here is a class you can simply paste into your mainwindow.h:
#include <QComboBox>
#include <QCompleter>
#include <QLineEdit>
#include <QWidget>
class MyComboBox : public QComboBox
{
Q_OBJECT
public:
explicit MyComboBox(QWidget *parent = 0) : QComboBox(parent){
setEditable(true);
completer()->setCompletionMode(QCompleter::PopupCompletion);
connect(lineEdit(), SIGNAL(editingFinished()), this, SLOT(removeOldestRow()));
}
//On Windows this is not needed as long as the combobox is editable
//This is untested since I don't have Linux
void showPopup(){
QComboBox::showPopup();
QWidget *popup = this->findChild<QFrame*>();
popup->move(popup->x(), popup->y()+popup->height());
}
private slots:
void removeOldestRow(){
if(count() == 6)
removeItem(0);
}
};
This combines both solutions into one class. Simply add this to your project and then change your QComboBox
declaration from this:
QComboBox* input = new QComboBox();
input->setEditable(true);
input->completer()->setCompletionMode(QCompleter::PopupCompletion);
input->setMaxCount(5);
to this:
MyComboBox* input = new MyComboBox();
I'm on Windows so I'm not able to test the exact result of the drop-down repositioning, but I think it will work. Please test it and let me know if it behaves how you want it to.
Upvotes: 6