可编辑QCombobox更改下拉位置

3
我创建了一个可编辑的QCombobox,存储最后的输入方式为:
QComboBox* input = new QComboBox();
input->setEditable(true);
input->completer()->setCompletionMode(QCompleter::PopupCompletion);
input->setMaxCount(5);

现在我有两个问题:
  1. 我想限制下拉菜单的大小,只显示最近的5个输入字符串。
  2. 这5个旧的输入应该全部显示在顶部可编辑行的下面。目前,旧的输入会遮挡住可编辑行。
对于第一个问题,调用 "setMaxCount(5)" 会使 QComboBox 显示插入的前五个项目,但我想要显示最后的五个项目。
对于第二个问题,我需要改变样式,所以我认为需要改变这些参数之类的东西:
  setStyleSheet("QComboBox::drop-down {\
              subcontrol-origin: padding;\
              subcontrol-position: bottom right;\
      }");

但我不知道要更改哪些参数才能使QComboBox输入行下仅显示最后5个条目。

编辑

这里有两张下拉菜单的图片。如您所见,我输入了5个条目,但编辑行被弹出窗口遮盖: enter image description here

enter image description here

在第二张图片中,编辑行位于标记条目“5”正后方。
1个回答

6
为了仅保留最后5个项目,您可以开始监听 QComboBoxQLineEdit 信号 editingFinished()。当发出信号时,您可以检查项目数,并在计数为6时删除最旧的项目。
要重新定位下拉菜单,您必须子类化QComboBox并重新实现 showPopup() 方法。从那里,您可以指定如何移动弹出式菜单。
这是一个可以简单粘贴到您的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);
    }
};

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

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

转换为:

MyComboBox* input = new MyComboBox();

我使用的是 Windows 系统,无法测试下拉菜单重新定位的确切结果,但我认为它会起作用。请测试并让我知道它是否表现出您想要的行为。


第一件事情進展順利 :) 我編輯了我的問題,所以你可以看到問題。彈出式選單會打開到頂部,隱藏了編輯行。 - Kapa11
1
@Kapa11 噢,我正在使用 Windows,所以它的行为不同。因为我无法测试它,所以很难给出答案。请查看我编辑后的回答。 - mrg95
太棒了!全部都符合我想要的。非常感谢 :) - Kapa11
1
@kapa11 很高兴我能帮到你 :) - mrg95

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接