[英]How to find out the type in internalPointer?
我有這樣的 model(在樹視圖中):
data1 - 一種類型 hello - 第二種類型
數據1
struct Group
{
QString name;
QList<Sample> samples;
}
你好
struct Sample
{
QString name;
}
我有插槽
void MainWindow::on_treeView_clicked(const QModelIndex &index)
{
Group *group = static_cast<Group *>(index.internalPointer());
ui->lineEdit->setText(group->name);
}
而且我需要確切地知道我在 internalPointer(Group 或 Sample)中選擇了哪種類型的項目。 因為類型轉換總是會發生,如果我使用static_cast<Group *>(index.internalPointer());
正如評論中所指出的,我強烈建議您對所有樹項目使用一個通用基礎 class。 這個基本的 class 應該為樹中需要的任何數據(名稱、圖標、子項數量等)聲明虛函數,然后在派生類中覆蓋這些數據,這些數據表示像組和樣本這樣的特化。 例子:
class TreeItem {
public:
virtual QString GroupName() const {return "";} //Returns an empty string as a default value
// any other common functions
}
class Group: public TreeItem {
public:
QString GroupName() const override {return m_name;}
private:
QString m_name;
}
class Sample: public TreeItem {
//Let GroupName() default to the base class implementation, or override if necessary
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.