C++ 将子项添加到自定义QStandardItem
我有一个目标:C++ 将子项添加到自定义QStandardItem,c++,qt,C++,Qt,我有一个目标: class Mando : public QObject, public QStandardItem { Q_OBJECT public: std::string getDescription() const; std::string getName() const; explicit Mando(boost::filesystem::path filen); private: boost::filesy
class Mando : public QObject, public QStandardItem {
Q_OBJECT
public:
std::string getDescription() const;
std::string getName() const;
explicit Mando(boost::filesystem::path filen);
private:
boost::filesystem::path file;
};
Q_DECLARE_METATYPE(Mando *)
Mando::Mando(boost::filesystem::path filen) {
file= filen; }
std::string Mando::getName() const {
return file.filename().string(); }
std::string Mando::getDescription() const {
return std::string("XxxxX"); }
和模型实施:
ContentModel::ContentModel() : QStandardItemModel() {
QStringList headers;
headers << tr("Name") << tr("Description");
setHorizontalHeaderLabels(headers);
setColumnCount(headers.count()); }
QVariant ContentModel::data(const QModelIndex &index, int role) const {
if(role == Qt::DisplayRole)
switch(index.column()) {
case 0: return static_cast<Mando*>(item(index.row()))->getName().c_str();
case 1: return static_cast<Mando*>(item(index.row()))->getDescription().c_str(); }
return QStandardItemModel::data(index, role); }
一切正常,我得到:
riri.ini XxxxX
fifi.ini XxxxX
loulou.ini XxxxX
但是,在某些情况下,我需要添加一个孩子
riri.ini XxxxX
-> riri's child YyyyY
fifi.ini XxxxX
loulou.ini XxxxX
-> loulou's child YyyyY
如果我在Mando实例中添加一个简单的行,如下所示:
model->appendRow(new Mando(boost::filesystem::path("/home/user/riri.ini")));
model->appendRow(new Mando(boost::filesystem::path("/home/user/fifi.ini")));
model->appendRow(new Mando(boost::filesystem::path("/home/user/loulou.ini")));
view= new QTreeView();
view.setModel(model);
Mando::Mando(boost::filesystem::path filen) {
file= filen;
appendRow(new QStandardItem() /* or */ QList<QStandardItem*>); }
Mando::Mando(boost::filesystem::path filen){
file=filen;
appendRow(新的QStandardItem()/*或*/QList);}
如何区分ContentModel::data中子项的父项?要将子项添加到项中,请在该项上使用
void QStandardItem::appendRow(QStandardItem*item)
。QStandardItem
还有方法child()
和parent()
,它们将帮助您识别是否存在家长/孩子。QModelIndex
类也是如此,因此它还可以帮助您确定是否存在与索引相关的子级或父级