如何在QGridLayout中获取QComboBox的当前文本?

How Can I get the Current Text of a QComboBox in QGridLayout?

本文关键字:文本 QComboBox 获取 QGridLayout      更新时间:2023-10-16

目前我有一个创建槽,当按下按钮时会调用它。Slot 函数需要从其上方 QGridLayout 中的组合框中获取所有数据。在上面的项目中,并非所有项目都有QComboBox。其中一些是QLineEdit,另一些是QLabel。我的QgridLayout称为ui.testgridLayout。

for (int i = 0; i < ui.testgridLayout->rowCount(); i++)
{
for (int j = 0; j < ui.testgridLayout->columnCount(); j++)
{
QLayoutItem *item= ui.testgridLayout->itemAtPosition(i, j);
if (item) {
if (strcmp(item->widget()->metaObject()->className(), "QComboBox")==0) {
QString objName= item->widget()->objectName();
QComboBox* cb =ui.testgridLayout->findChild<QComboBox*>(objName);
string text = cb->currentText().toLocal8Bit().constData();
}
}
}
}

目前,这会在 ConfigFileCreation.exe 中返回 0x00007FFB107DCC8A (Qt5Widgets.dll( 处的未处理异常: 0xC0000005:访问冲突读取位置0x0000000000000008。任何帮助或建议将不胜感激。

问题是你认为放置在布局中的小部件是布局的子项,但不,这些小部件是建立布局的小部件的子项,所以在你的代码中,"cb"是一个导致问题的空指针。解决方案是强制转换并验证指针是否有效:

for (int i = 0; i < ui.testgridLayout->rowCount(); i++){
for (int j = 0; j < ui.testgridLayout->columnCount(); j++){
if (QLayoutItem *item= ui.testgridLayout->itemAtPosition(i, j)) {
if (QComboBox* cb  = qobject_cast<QComboBox*>(item->widget())) {
string text = cb->currentText().toLocal8Bit().constData();
}
}
}
}