Create new class with many argument



  • Hello,

    It is surely simple, but since yesterday I am trying to create a class with several arguments (shame ....).

    Currently I use this example to run my code :

    //myobject1.h
    class MyPainter1 : public QObject
    {
    public:
        explicit MyPainter1(QObject *parent = 0);
    
    private slots:
    
    public slots:
        void test();
        void setPainter(QPainter *painter);
    
    public:
        QPainter *m_painter;
    };
    
    
    //myobject1.cpp
    #include "myobject1.h"
    
    MyPainter1::MyPainter1(QObject *parent) : QObject(parent)
    {
    
    }
    
    void MyPainter1::test()
    {
        QRectF m_headerRect(0, 350, 300, 250);
    
        m_painter->setPen(Qt::yellow);
        m_painter->drawRect(m_headerRect);
        qDebug() << "this is a test";
    }
    
    void MyPainter1::setPainter(QPainter *painter)
    {
        m_painter = painter;
    }
    
    //and the use where painter is a QPainter which is defined rather :
    MyPainter1 myObj;
    myObj.setPainter(painter);
    myObj.test();
    

    This works, but finally, I would prefer use MyPainter this way :

    MyPainter1 myObj(painter)
    myObj.test();
    

    But I can't find a way to build my class correctly.

    Can you help me ?

    Thank you in advance.

    Charlie.



  • Several problems here:

    • missing Q_OBJECT macro
    • uninitialised m_painter (calling test before calling setPainter crashes)
    • no checks on m_painter (calling setPainter with a null pointer argument and then calling test crashes)
    • m_painter is in the public section despite having an encapsulated setter (setPainter)
    class MyPainter1 : public QObject
    {
    Q_OBJECT
    public:
        explicit MyPainter1(QPainter *painter=Q_NULLPTR, QObject *parent = Q_NULLPTR)
    :QObject (parent), m_painter(painter){}
    
    public slots:
        void test(){
    if(!m_painter) return;
        QRectF m_headerRect(0, 350, 300, 250);
    
        m_painter->setPen(Qt::yellow);
        m_painter->drawRect(m_headerRect);
        qDebug() << "this is a test";
    }
        void setPainter(QPainter *painter){
        m_painter = painter;
    }
    private:
        QPainter *m_painter;
    };
    


  • This is super... Thank you very much.

    I really have to do more C++ and a (little) less QML :-).


Log in to reply
 

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