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

Declaring an array from const int



  • Hello

    I am trying to make a grid of buttons, using a widget application. In the Widget class I have added two private const int for how many rows and columns:

    class Widget : public QWidget
    {
        Q_OBJECT
    
    public:
        Widget(QWidget *parent = nullptr);
    
    private:
        QSize sizeHint() const;
        const int windowWidth = 600;
        const int windowHeight = 600;
        const int columns = 8;
        const int rows = 8;
    
    };
    

    In the constructor for widget class I then initialize an array of pointer to QPushButton using the constants columns and rows:

    QPushButton * buttons[columns][rows];
    

    At compile time this leads to an error:
    "expression does not evaluate to a constant,
    failure was caused by a read of a variable outside its lifetime,
    see usage of this"

    I know that you cannot initialize an array using variables, but it should be possible using constants. I tried to do the same outside QT (with an array of pointers to integers) and it worked fine.

    So is this problem something specific to QT, or is there something fundamental that I am missing?


  • Lifetime Qt Champion

    @saa_ said in Declaring an array from const int:

    I tried to do the same outside QT (with an array of pointers to integers) and it worked fine.

    But only with a gcc compiler and enabled gcc extensions.
    Use constexpr instead const to make it a real compile-time constant.


  • Lifetime Qt Champion

    @saa_ said in Declaring an array from const int:

    I tried to do the same outside QT (with an array of pointers to integers) and it worked fine.

    But only with a gcc compiler and enabled gcc extensions.
    Use constexpr instead const to make it a real compile-time constant.



  • You mean someting like this?

    std::vector<QPushbutton*> myButtons(columns * rows, nullptr);
    y = 4; // [0..7]
    x = 1; // [0..7]
    myButtons[ columns * y + x ] = new QPushbutton();
    

    or any of the dynamic containers that could serve you well.


Log in to reply