Class definition issue



  • Hi,
    I have the following class in mydelegate.h:

    #ifndef MYDELEGATE_H
    #define MYDELEGATE_H
    
    #include <QObject>
    #include <QWidget>
    #include <QStyledItemDelegate>
    #include <QStyleOptionViewItem>
    #include <QLineEdit>
    #include <QDebug>
    
    namespace Ui
    {
    class myDelegate;
    }
    
    class myDelegate : public QStyledItemDelegate
    {
        Q_OBJECT
    
    public:
        explicit myDelegate(QWidget *parent = nullptr);
    

    The mydelegate.cpp:

    #include "mydelegate.h"
    
    
    myDelegate::myDelegate(QWidget *parent)
    {
    }
    

    Whenever I run it I get the following warning:
    C:\Programming\Projects\Folkfriends_1_0\mydelegate.cpp:4: warning: unused parameter 'parent' [-Wunused-parameter]
    myDelegate::myDelegate(QWidget *parent)
    ^
    Everything works.Do I need to worry about this (and other unused parameter) warning?
    Thank you.


  • Moderators

    @gabor53 said:

    Do I need to worry about this (and other unused parameter) warning?

    Yes, because it uncovered a serious bug in your code. In your constructor definition you're not passing the parameter to the base class constructor, so it calls a default base constructor, making your instance not having a parent (and thus creating a memory leak).

    When creating QObject derived classes always pass the parent parameter to the base class constructor:

    myDelegate::myDelegate(QWidget* parent) : QStyledItemDelegate(parent)
    {
    }
    

    Btw. It's unusual that an item delegate would need a parent QWidget. QObject should be enough:

    //.h
    explicit myDelegate(QObject* parent = nullptr);
    
    //.cpp
    myDelegate::myDelegate(QObject* parent) : QStyledItemDelegate(parent)
    


  • @Chris-Kawa
    Thank you. It worked.


Log in to reply
 

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