Qt - How to convert from QObject to UI elements?

时光怂恿深爱的人放手 提交于 2019-12-01 22:09:59

You should think about using qobject_cast. After the cast you should also check if the object is valid.

QStringList textlist;
for(int i = 0; i < ui->myWidget->children().size(); i++)
{
    if(i % 2 == 0)
    {
        QCheckBox *q = qobject_cast<QCheckBox*>(ui->myWidget->children().at(i));
        if(q)
           textlist.append(q->text());
    }
    else
    {
        QComboBox *q = qobject_cast<QComboBox*>(ui->myWidget->children().at(i));
        if(q)
           textlist.append(q->currentText());
    }
}

But this still seems like a bad design to me. The widget class that contains the comboboxes and checkboxes should have a function, that goes through the checkboxes and comboboxes and returns a QStringList. Then you could just call that function.

Here is an example

mywidget.h:

namespace Ui {
class MyWidget;
}

class MyWidget : public QWidget
{
    Q_OBJECT

public:
    explicit MyWidget(QWidget *parent = 0);
    ~MyWidget();
    QStringList getComboTextList();
    QStringList getCheckBoxTextList();

private:
    Ui::MyWidget *ui;
    QList<QComboBox*> comboList;
    QList<QCheckBox*> checkList;
};

  mywidget.cpp:

MyWidget::MyWidget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::MyWidget)
{
    ui->setupUi(this);
    this->setLayout(new QVBoxLayout);
    for(int i = 0; i < 5; i++)
    {
        QCheckBox *checkBox = new QCheckBox(this);
        this->layout()->addWidget(checkBox);
        checkBox->setText(QString("Check box #%1").arg(i));
        checkList.append(checkBox);
    }

    for(int i = 0; i < 5; i++)
    {
        QComboBox *comboBox = new QComboBox(this);
        this->layout()->addWidget(comboBox);
        comboBox->addItem("Combo box item 1");
        comboBox->addItem("Combo box item 2");
        comboList.append(comboBox);
    }
}

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

QStringList MyWidget::getComboTextList()
{
    QStringList returnList;
    for(int i = 0; i < comboList.length(); i++)
    {
        returnList << comboList[i]->currentText();
    }
    return returnList;
}

QStringList MyWidget::getCheckBoxTextList()
{
    QStringList returnList;
    for(int i = 0; i < checkList.length(); i++)
    {
        returnList << checkList[i]->text();
    }
    return returnList;
}

Then in your other class you can just call getCheckBoxTextList or getComboTextList like this:

QStringList comboTextList = myWidget->getComboBoxList();
QStringList checkTextList = myWidget->getCheckBoxTextList();
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!