Please nominate your Qt Champions for 2021!

Display the QListView as drop down on clicking a button

  • Hi,

    I am looking for a solution to display the QListView as a drop down on clicking a button. I tried the following way code,the QListWidget is not coming exactly below the button. it is coming at a different place. Also on re click of the button,the QListWidget should disappear.

    QPushButton *b = new QPushButton("Click Me");	
    QListWidget *w = new QListWidget();
    w->setWindowFlags(Qt::Dialog | Qt::MSWindowsFixedSizeDialogHint | Qt::WindowStaysOnTopHint);
    w->setWindowFlags(Qt::Dialog | Qt::FramelessWindowHint | Qt::WindowStaysOnTopHint);
    w->setWindowFlags(Qt::Popup | Qt::FramelessWindowHint | Qt::WindowCloseButtonHint);
    QStringList items;
    items << "foo" << "bar" << "baz";
    w->move(600, 66);
    QObject::connect(b, SIGNAL(clicked()), w, SLOT(show()));

    Any suggestion on this.

    /edit by moderation: added code tags

  • @thomasjohnaj
    I'm not sure whether my situation helps with whatever you are trying to obtain exactly. But recently I wanted a popup widget to appear "touching" the QPushButton which is used to display it. I had problems getting the coordinates correct. The following works:

    UIUtils::PushButtonWithPopup::PushButtonWithPopup(QWidget *parent /*= nullptr*/) :
        QCommonStyle style;
        // popup window flags (popup with no frame)
        _popup.setWindowFlags(Qt::Popup | Qt::FramelessWindowHint);
        // popup as small as possible
        _popup.setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Minimum);
        // connect button click to execute the popup
        connect(this, &QPushButton::clicked, this, &UIUtils::PushButtonWithPopup::doPopup);
    /*slot*/ void UIUtils::PushButtonWithPopup::doPopup()
        // position the popup just above the button
        QPoint pos = this->mapToGlobal(QPoint(0, 0));
        // show the popup;
        // can only get its height to position it after it is shown
        _popup.move(pos.x(), pos.y() - _popup.height());

    The important thing being the QPoint pos = this->mapToGlobal(QPoint(0, 0));.

    Once the popup is shown, user must click anywhere outside the popup to dismiss.

  • @JonB I positioned it below the button with the sample code attached, but I have to address two issues

    1. the dropdown should go off on pressing the button again
    2. the dropdown windows should have the top priority

  • @thomasjohnaj said in Display the QListView as drop down on clicking a button:

    the dropdown should go off on pressing the button again

    All I know is if you click outside mine it disappears. Doesn't matter where, button or not.

Log in to reply