Key press event in a templated class



  • I just discovered that Q_OBJECTs and templates don't mix. I have a small templated
    class that needs to listen for a QLineEdit's returnPressed signal. What is the best way
    to do this? With installEventFilter? What is the event code? Thanks!



  • You can create a private helper class which inherits QObject, instantiate one object in your template class and use this as the receiver for the signal (connect is a static method - your template class can just call QObject::connect(...))



  • The difficulty for me is, this helper class would need a reference to an instance of a template class. Can I do that without the helper class being templated? The only kludgey way I can
    see to do this is to use a helper class and an interface. I'm new at C++ templates so
    maybe I'm missing something.

    Here's some pseudo-code.

    This is what I wish I could do, but can't because of the q_object/template thing:

    @
    template <class T>
    class Foo {

    constructor {
    QTableView table...
    connect(table, doubleClicked, doubleClicked)
    }

    slot doubleClicked {
    T t = ... calculated from QModelIndex
    handler.handle(t)
    }

    Handler<T> handler; // member

    }
    @

    This is my hack. How can I do this better?

    @
    class Interface { public: callBackIndex(QModelIndex) }

    class Helper {

    Q_OBJECT

    slot doubleClicked { callback.callbackIndex(QModelIndex); }

    Interface callback; // member

    }

    template <class T>
    class Foo : public Interface {

    constructor {
    QTableView table...
    connect(table, doubleClicked, helper.doubleClicked)
    }

    callbackIndex {
    T t = ... calculated from QModelIndex
    handler.handle(t)
    }

    Helper helper (this); // member
    Handler<T> handler; // member

    }

    @

    The handler is being passed into Foo and Foo has a couple other templated members as well.
    I just don't know how to pass in a reference to Foo in Helper without Helper being templated as well.
    If I try to pass it in as a pointer with no template parameter it is an error: Helper::Helper(Foo* foo)



  • Bump.



  • Depending on what T you intend your template for, you can consider using QVariant instead.


Log in to reply
 

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