使用QString或string调用结构对象

问题描述 投票:0回答:2

我想从struct的对象中获取结果。

allitems.h

#ifndef ALLITEMS_H
#define ALLITEMS_H
#include <QString>
class allitems
{
public:
    allitems();
    struct magazalar{
        QString rev;
    }kfc;
};
#endif // ALLITEMS_H

item.cpp

#include "allitems.h"
allitems::allitems()
{
    kfc.rev="2";
}

现在我想从另一个cpp文件中获取kfc.rev的结果

void MainWindow::clicked(){
    allitems aaa;
    QPushButton *xx=(QPushButton *)sender();
    //xx->objectName() returns "kfc"
    qDebug()<<aaa.(xx->objectName()).rev;
}

我想用点击按钮调用kfc.rev。当我点击按钮按钮objectname是kfc我可以采取结果,但我无法实现从按钮对象名调用结构数据

有什么想法解决它吗?

c++ qt struct
2个回答
0
投票

使用sender()通常是不好的代码味道,并且表明你应该做其他事情。

在现代C ++中,您可以在连接按钮时轻松生成必要的代码。让我们假设aaaMainWindow的成员:

MainWindow::MainWindow(QWidget * parent) : QMainWindow(parent) {
  auto const clicked = &QPushButton::clicked;
  connect(ui->kfc, clicked, [this]{ qDebug() << this->aaa.kfc.rev; });
  //more connect statements here...
}

3
投票

你不能这样做:

qDebug()<<aaa.(xx->objectName()).kat;

它是无效的C ++,这个:(xx->objectName())必须在编译时知道,而不是在运行时。如果要在运行时使其工作,则需要使用map或if语句:

在这里你可以使用简单的if-s:

if (xx->objectName() == "kfc")
 qDebug()<<aaa.kfc.kat;
//else if (xx->objectName() == "some_other_kfc")
// qDebug()<<aaa.some_other_kfc.kat;

但我不认为它是最好的设计,通常你会联系一个按钮,一个单击处理程序,它知道要修改哪个结构 - 而且它不需要从按钮实例中获取这些知识。

© www.soinside.com 2019 - 2024. All rights reserved.