Search code examples
c++qtqcombobox

I want to use the QComboBox with an Event (Return) in QT


I have the following problem:

I'm using the QComboBox of QT to select a path by a Drop & Down. It is working fine after I choose one of the list, the path is automatically update. But now if I want to edit the Path manually by type in a path, I get immediately a warning. So I know that this is happening cause of the argument:

QComboBox::currentTextChanged

So always if I'm going to change the path, for example by changing only one letter or select it by Drop & Down the "currentTextChanged" and a new function will be called. For example the function:

nextstep()

So what I want to achieve is that if I'm going to select a path the function should be called normally. But if I'm going to type in a new path or editing the path manually I want that the function will be called after type "return".


Solution

  • You could subclass QComboBox and define a new signal in your class that's emitted only when the user types enter or when the index is changed.
    To do that you must connect your new signal to QComboBox::lineEdit()'s returnPressed() or editingFinished() signals and to QComboBox::currentIndexChanged().
    I chose editingFinished() but you can try the other one too.
    All that is left is to connect nextstep() to currentTextSaved()

    To use MyComboBox in the .ui files, you have to promote the existing QComboBoxes to it.
    Here's the official documentation: https://doc.qt.io/qt-5/designer-using-custom-widgets.html

    mycombobox.h

    #ifndef MYCOMBOBOX_H
    #define MYCOMBOBOX_H
    
    #include <QComboBox>
    
    class MyComboBox : public QComboBox
    {
        Q_OBJECT
    public:
        MyComboBox(QWidget *parent = nullptr);
    
    signals:
        void currentTextSaved(const QString &text);
    };
    
    #endif // MYCOMBOBOX_H
    

    mycombobox.cpp

    #include "mycombobox.h"
    
    #include <QLineEdit>
    
    MyComboBox::MyComboBox(QWidget *parent)
        : QComboBox(parent)
    {
        connect(lineEdit(), &QLineEdit::editingFinished,
                this, [&] () { emit currentTextSaved(currentText()); });
        connect(this, QOverload<int>::of(&QComboBox::currentIndexChanged),
                this, [&] (int index) { Q_UNUSED(index) emit currentTextSaved(currentText()); });
    }
    

    Here's an example: https://www.dropbox.com/s/sm1mszv9l2p9yqd/MyComboBox.zip?dl=0

    This old post was useful https://www.qtcentre.org/threads/26860-Detecting-Enter-in-an-editable-QComboBox