summaryrefslogtreecommitdiffstats
path: root/src/corelib/doc/snippets/qtcast/qtcast.cpp
blob: cf7f722c30f2aa356df15789f6cb773eb06c03dc (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
// Copyright (C) 2016 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause

#include <QLabel>
#include <QPushButton>

#include "qtcast.h"

MyWidget::MyWidget()
{
//! [0]
    QObject *obj = new MyWidget;
//! [0]

//! [1]
    QWidget *widget = qobject_cast<QWidget *>(obj);
//! [1]

//! [2]
    MyWidget *myWidget = qobject_cast<MyWidget *>(obj);
//! [2]

//! [3]
    QLabel *label = qobject_cast<QLabel *>(obj);
//! [3] //! [4]
    // label is nullptr
//! [4]

//! [5]
    if (QLabel *label = qobject_cast<QLabel *>(obj)) {
//! [5] //! [6]
        label->setText(tr("Ping"));
    } else if (QPushButton *button = qobject_cast<QPushButton *>(obj)) {
        button->setText(tr("Pong!"));
    }
//! [6]
}