更改可编辑 QCombobox 的下拉位置

Change Dropdown-Position of editable QCombobox

我创建了一个可编辑的 QCombobox,用于存储最后的输入:

QComboBox* input = new QComboBox();
input->setEditable(true);
input->completer()->setCompletionMode(QCompleter::PopupCompletion);
input->setMaxCount(5);

现在我遇到了 2 个问题:

  1. 我想将下拉菜单的大小限制为最后 5 个输入字符串。

  2. 这 5 个旧输入应全部显示在下方 顶部的可编辑行。目前,旧输入隐藏了可编辑行。

对于第一个方面,调用“setMaxCount(5)”使 QComboBox 显示插入的 first 5 个项目,但我希望它显示 last 5 项。

对于第二个方面,我不知何故需要按照我的想法改变风格。所以改变……喜欢这些参数:

  setStyleSheet("QComboBox::drop-down {\
              subcontrol-origin: padding;\
              subcontrol-position: bottom right;\
      }");

但我不知道这里要更改哪些参数 s.t。只有最后 5 个条目全部显示在 QComboBox 的输入行下。

编辑

这里有两张显示下拉菜单的图片。如您所见,我输入了 5 个条目,但编辑行被弹出窗口隐藏了:

在第二张图片中,编辑行就在标记条目“5”的后面。

为了仅保留最后 5 个项目,您可以先监听 QComboBoxQLineEdit 信号 editingFinished()。发出信号后,您可以检查项目计数,如果计数为 6,则删除最旧的项目。

要重新定位下拉菜单,您必须子class QComboBox 并重新实现showPopup() 方法。从那里您可以指定如何移动弹出菜单。

这是一个 class 您可以简单地粘贴到您的 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);
    }
};

这将两个解决方案合并为一个 class。只需将其添加到您的项目中,然后更改您的 QComboBox 声明:

QComboBox* input = new QComboBox();
input->setEditable(true);
input->completer()->setCompletionMode(QCompleter::PopupCompletion);
input->setMaxCount(5);

对此:

MyComboBox* input = new MyComboBox();

我在 Windows 所以我无法测试下拉重新定位的确切结果,但我认为它会起作用。请对其进行测试,如果它的行为符合您的要求,请告诉我。