macro/keyboard shortcut to auto-gen slot/signal for variable

  • I would like to be able to define a macro in QtCreator that would allow me to create a "mutator slot with signal" automatically in my C++ header file. For example, if the cursor is on a variable such as:
    QList<Frob> m_yadda;
    it would be nice to auto-generate in the "signals:" section the following:
    and in the "public slots:" section the following:
    void setYadda(QList<Frob> newYadda) { m_yadda = newYadda; emit yadda(m_yadda); }

    I find that I cannot look at the Tools->Options->Environment->Keyboard and type in the text editing window to generate a macro for this at the same time. This makes it a bit of a challenge. Ideally I'd like to create this macro and save it to a key binding so that it is always available. Are there any macro ninjas who could take a stab at creating this macro or adding it as a default feature to QtCreator? Either that or tell me what I'm missing to be able to generate this. I can do it in emacs, and eclipse has the ability to generate setter/getters as a built-in. I just want it in QtCreator.

  • can you try this, maybe it not exactly what you want,

    #define PROPERTY(type, name)\
        Q_PROPERTY(type name READ get_##name WRITE set_##name NOTIFY name##Changed)\
        type name;\
        type get_##name() const {return name;}\
        void set_##name(type name) { if(this->name != name) {this->name=name; emit name##Changed();}}\
        Q_SIGNAL void name##Changed();

    Then in class you just need using it

    Class Person: public QObject {
    Q_PROPERTY(QString, name)

    [edit:koahnig] Code markers

  • Moderators


    Usage would be:

    Class Person: public QObject {
        PROPERTY(QString, name)

    Wouldn't it?

  • Qt Champions 2017

    Right clicking on a QString m_testText member and selecting Refactor > Create Getter and Setter Member Functions does most of what you want. For me (Qt Creator 4.0.3) it generates:

    QString TestClass::testText() const
        return m_testText;
    void TestClass::setTestText(const QString & testText)
        m_testText = testText;

    As for macros, I don't know if Qt creator supports macros.

  • @koahnig , sorry, actually, we need define one constructor for this, i define another macro,
    #define BEGIN_MODEL(name)\
    class name: public QObject\
    name(QObject *parent = 0): QObject(parent){}\
    virtual ~name(){}

    #define END_MODEL };

    Then declare one model object like
    PROPERTY(QString, name)

    i not move Q_OBJECT to macro BEGIN_MODEL, because it relate to qmake that generate moc_ files and cause error,
    this is one way to simple define model,
    ps: but using macro is not recommended, because it have some trouble for debug

Log in to reply

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