首页 文章

更改下拉列表 - 可编辑QCombobox的位置

提问于
浏览
0

我创建了一个可编辑的QCombobox,通过以下方式存储最后的输入:

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

现在我有两个问题:

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

  • 这5个旧输入都应显示在顶部的可编辑行 . 目前,旧输入隐藏了可编辑行 .

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

对于第二个方面,我不知何故需要改变我的想法 . 所以改变某事 . 像这些参数:

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

但我不知道这里有哪些参数可以改变s.t.只有最后5个条目都显示在QComboBox的输入行下面 .

EDIT

以下是下拉菜单如何显示的两张图片 . 我输入了5个条目你可以看到,但编辑行被弹出窗口隐藏了:
enter image description here

enter image description here

在第二张图片中,编辑行位于标记条目“5”的正后方 .

1 回答

  • 1

    为了只保留最后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上,所以我无法测试下拉重新定位的确切结果,但我认为它会起作用 . 请测试它并告诉我它是否符合您的要求 .

相关问题