【问题标题】:Change Dropdown-Position of editable QCombobox更改可编辑 QCombobox 的下拉位置
【发布时间】:2017-04-11 13:10:10
【问题描述】:

我创建了一个可编辑的 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;\
      }");

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

编辑

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

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

【问题讨论】:

    标签: qt drop-down-menu qcombobox


    【解决方案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 上,所以我无法测试下拉重新定位的确切结果,但我认为它会起作用。请对其进行测试,如果它的行为符合您的要求,请告诉我。

    【讨论】:

    • 第一件事效果很好:) 我编辑了我的问题,所以你可以看到问题。弹出菜单打开到顶部隐藏编辑行。
    • @Kapa11 啊,我在 Windows 上,所以它的行为不同。我很难找到答案,因为我无法测试它。请查看我编辑的答案。
    • 太棒了!一切如我所愿。非常感谢:)
    • @kapa11 很高兴我能帮上忙 :)
    猜你喜欢
    • 1970-01-01
    • 2017-01-07
    • 2019-11-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-26
    • 1970-01-01
    • 2013-04-11
    相关资源
    最近更新 更多