Set parent text of status bar?

I can set the text of the status bar of the parent using this function that I wrote

void EditorWindow::setStatusBarText(const QString& text) {
    statusBar()->showMessage(text);
}

Called like this (from a child)

((EditorWindow*) parent())->setStatusBarText(tr("%1, %2").arg(mousePos.x(), 0, 'f', 2).arg(mousePos.y(), 0, 'f', 2));

But I'm sure that violates several design principles. For example, what if parent()not EditorWindow*?

So what is the workaround for this? Force the user to pass a link to EditorWindowat creation to ensure that the parent type is of the correct type?

+3
source share
1 answer

Use signals and slots;

Make a EditorWindow::setStatusBarTextslot. Give your child a signal when he wants to change status, and connect him to the slot setStatusBarText.

// make setStatusBarText a slot...
class EditorWindow : public QWidget {
    Q_OBJECT
    ...
    public slots:
        void setStatusBarText(const QString&);
}

// make a signal to be emitted when status should change:
class SomeChildWidget : public QWidget {
    Q_OBJECT
    ...
    signals:
        void statusEvent(const QString&);
}

// connect them up when appropriate
EditorWindow::EditorWindow()
 : QWidget()
{
    ...
    m_childWidget = new SomeChildWidget(this);
    connect(m_childWidget, SIGNAL(statusEvent(QString)),
            this,          SLOT(setStatusBarText(QString)));
    ...
}

emit statusEvent(somestring), .

, , , , , .

+9

Source: https://habr.com/ru/post/1715293/


All Articles