Template function



  • In .cpp file I have this template function:

    template <typename M, typename N> void MainWindow::showMenu(M m, N n)
    {
        QSize size = m->sizeHint();
        m->popup(n->mapToGlobal(QPoint(0,0-size.height())));
    }
    

    where
    · m = QMenu
    · n = QPushPutton

    In what form I should declare this function in the header file?

    Thanks in advanve


  • Qt Champions 2016

    @UnitScan

    What about MainWindow.h ?

    Also since all QWidgets are QObjects, you dont need templates for most GUI operations.



  • connect(sel, SIGNAL(released()), this, SLOT(showMenu(QMenu, QPushButton)));
    
    void MainWindow::showMenu(QMenu *m, QPushButton *pb)
    {
        QSize size = m->sizeHint();
        m->popup(pb->mapToGlobal(QPoint(0,0-size.height())));
    }
    

    Doesn't work


  • Qt Champions 2016

    @UnitScan said in Template function:

    Hi
    That is because the released() signal DO NOT have QMenu* and QPushButton * parameters.

    You cannot invent new parameters for a signal.
    You can define new signals though.

    http://doc.qt.io/qt-5/signalsandslots.html

    also note that connect returns true if connect works.

    so

    qDebug() << "tcheck:" << connect(xxx) to see if they work.



  • SOLVED

    void MainWindow::showMenu()
    {
        QPushButton *pb = qobject_cast<QPushButton*>(sender());
        QMenu* m = qobject_cast<QMenu*>(pb->children().at(0));
        QSize size = m->sizeHint();
        m->popup(pb->mapToGlobal(QPoint(0,0-size.height())));
    }
    

  • Qt Champions 2016

    @UnitScan

    Hi you should check both pb an m for not being null :)



  • since I hate sender() and pb->children().at(0) is even less robust I suggest (assuming you declared QMenu* MainWindow::m):

    connect(sel, &QPushButton::released, [=]()->void{
    const QSize size = m->sizeHint();
    m->popup(sel->mapToGlobal(QPoint(0,-size.height())));
    });
    

    P.S.
    Looking at this functionality, are you sure QToolButton is not a better choice? see QToolButton::setMenu


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.