Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

How to parent QPainter to QTabWidget?



  • Hi!

    I'm creating paint software which has tabs with Qt.
    I want to add the QPainter to each tab(Created with the QTabWidget).
    But the QPainter's function doesn't have the "QWidget *parent" property.
    How should I do?
    (I'm Japanese, so please forgive my poor English.)


  • Lifetime Qt Champion

    Hi
    Use a custom widget for each tab so you can override paintEvent.

    #include <QPainter>
    #include <QWidget>
    
    class Canvas : public QWidget
    {
        Q_OBJECT
    public:
        explicit Canvas(QWidget *parent = nullptr) : QWidget(parent)
        {
    
        }
    protected:
        virtual void paintEvent(QPaintEvent *event) override
        {
            QPainter p(this);
            p.drawRect(0, 0, 100, 100);
        }
    };
    

  • Lifetime Qt Champion

    You can't attach a painter to something. You can create a QPainter in the QWidget::paintEvent() to draw on the widget.


  • Lifetime Qt Champion

    Hi
    Use a custom widget for each tab so you can override paintEvent.

    #include <QPainter>
    #include <QWidget>
    
    class Canvas : public QWidget
    {
        Q_OBJECT
    public:
        explicit Canvas(QWidget *parent = nullptr) : QWidget(parent)
        {
    
        }
    protected:
        virtual void paintEvent(QPaintEvent *event) override
        {
            QPainter p(this);
            p.drawRect(0, 0, 100, 100);
        }
    };
    


  • I've got the thing I want to do. Thanks a lot!


Log in to reply