0

Всем привет! Такой вопрос, как мне достать определенный виджет из лойаута.

Например у меня есть такая конструкция:

QHBoxLayout * pLayout = new QHBoxLayout(parent);
QRadioButton * item = new QRadioButton(parent);
QPushButton * button = new QPushButton(parent);
pLayout->addWidget(item);
pLayout->addWidget(button);
layout->addLayout(pLayout);

И мне нужно достать из этой конструкции радиобаттон, например так:

for (size_t i = 0, sz = N; i < sz; ++i)
{
    QWidget * selectorWidget = layout->itemAt((int)i)->widget();
}
QRadioButton* item  = qobject_cast<QRadioButton*>(selectorWidget);

1 ответ 1

2

Можно использовать поиск потомка findChild по имени объекта:

//MainWindow.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QHBoxLayout>
#include <QVBoxLayout>
#include <QRadioButton>
#include <QPushButton>
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    QVBoxLayout * vLayout = new QVBoxLayout();
    QHBoxLayout * pLayout = new QHBoxLayout();
    QRadioButton * item = new QRadioButton();
    item->setObjectName("radioBtn");
    QPushButton * button = new QPushButton();
    button->setObjectName("pushBtn");
    pLayout->addWidget(item);
    pLayout->addWidget(button);
    vLayout->addLayout(pLayout);
    centralWidget()->setLayout(vLayout);
}

MainWindow::~MainWindow()
{
    delete ui;
}

Поиск элементов по имени:

//main.cpp
#include "mainwindow.h"
#include <QApplication>
#include <QPushButton>
#include <QRadioButton>
#include <QLayout>
#include <QDebug>
int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    MainWindow w;
    w.show();
    QPushButton* el = w.centralWidget()->findChild<QPushButton*>("pushBtn");
    if (el){
        el->setEnabled(false);
    }else{
        qInfo() << "can't find push";
    }
    QRadioButton* radioBtn = w.centralWidget()->findChild<QRadioButton*>("radioBtn");
    if (radioBtn){
        radioBtn->setChecked(true);
    }else{
        qInfo() << "can't find radio";
    }
    return a.exec();
}

Вместо конкретных типов кнопок можно указывать параметров шаблона QWidget*, а потом в зависимости от objectName делать qobject_cast к нужному типа кнопки.

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.