2017-04-17 55 views
1

考虑以下几点:需要一个Qt解决方法铸造一个基地到另一个

class MyInterface { /* ... */ }; // has virtual methods and all 

class MyToolButton : public QToolButton, public MyInterface { /* ... */ }; 

class MyRadioButton : public QRadioButton, public MyInterface { /* ... */ }; 

class MyFrame : public QFrame { /* ... */ }; 

void MyFrame::doesNotWork() 
{ 
    for(int i = 0; i < layout()->count(); ++i) 
    { 
     QLayoutItem *item = layout()->itemAt(i); // can be either MyToolButton or MyRadioButton 
     Q_ASSERT(item); // passes 
     MyInterface *interface = dynamic_cast<MyInterface*>(item); 
     Q_ASSERT(interface); // TRIGGERS 
    } 
} 

有一些有创意的Qt的方式来获得一个指向MyInterface这里? QLayoutItem不会从QObject继承,这有点令人伤心。

+2

这里不是Qt开发者,但是'QadioButton'是'QObject'。它是一个'QLayoutItem'吗?尝试调用布局项目上的“小部件”,然后投射? – Yakk

+0

@Yakk哈!调用'widget()'并从'QWidget'强制转换的确可以解决它。谢啦。 – sigil

回答

4

QLayoutItems不是小部件;如果一个小部件(或其他)被定位,它们就是抽象的。要获取小部件,请在布局项目上拨打widget()。然后dynamic_cast。