简体   繁体   中英

How to fix "cannot initialize a variable of type 'QGraphicsProxyWidget *' with an rvalue of type 'QGraphicsLayoutItem *'"?

I want to parse the QGraphicsGridLayout , but getting this error. The thing is I was able to add QGraphicsProxyWidget as an item but not able to retrieve it. I want to know how to convert a QGraphicsLayoutItem* to QGraphicsProxyWidget* in this line of retrieving code QGraphicsProxyWidget *currentWidget = layout->itemAt(row, col); . please help.

adding:

int numCols = 4,row = 0,col = 0;
for(int index = 0; index < node_vector.size(); index++){

    QString node = node_vector[index];

    QLabel *label = new QLabel;
    label->setText(node);
    label->setAlignment(Qt::AlignCenter);
    label->setMargin(5);
    label->setStyleSheet("border: 1px solid black; background: white;");

    QGraphicsProxyWidget *stringLabel = scene->addWidget(label);
    layout->addItem(stringLabel,row+1, col+1);

    col++;
    if(col == numCols) row++;
    col = col % numCols;
}

retrieving:

int itemCount = layout->count();

int numCols = 4;
int row = 0, col = 0;
for (int i = 0; i < itemCount; ++i)
{
    auto *currentWidget = static_cast<QGraphicsProxyWidget*>(layout->itemAt(row, col));

    QPalette p(palette());
    p.setColor(QPalette::Background, Qt::blue);
    if (currentWidget) currentWidget->setPalette(p);
    else qDebug() << "getting nullptr";

    col++;
    if (col == numCols) row++;
    col = col % numCols;
}

Cause

QGraphicsProxyWidget is a QGraphicsWidget , which in turn is both QGraphicsObject and QGraphicsLayoutItem .

QGraphicsGridLayout::itemAt returns QGraphicsLayoutItem , hence by writing this:

QGraphicsProxyWidget *currentWidget = layout->itemAt(row, col);

the compiler recognizes only the QGraphicsLayoutItem -part of this multiple inheritance and gives you an error.

Solution

Cast layout->itemAt(row, col) explicitly to QGraphicsProxyWidget like this:

auto *currentWidget = static_cast<QGraphicsProxyWidget *>(layout->itemAt(row, col));

Note: You have to be sure, that the item at this position is indeed QGraphicsProxyWidget . If you have some kind of QGraphicsLayout instead, your program will crash.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM