I must adding a row in a QTableWidget. Previously I add all rows with a size of a list, like this:
MyProgram::MyProgram( QWidget* parent )
: QDialog( parent )
, ui( new Ui::MyProgram )
{
ui->setupUi( this );
QStringList allFiles = QDir( "~/" ).entryList( QStringList << "*.txt" );
ui->myQTableWidget->setRowCount( allFiles.size() );
for( int cont = 0; cont < allFiles.size(); ++cont )
{
//insert values in my QTableWidget
}
}
But now I can't know how many files I will show in QTableWidget, because I added a validation before. It like this:
MyProgram::MyProgram( QWidget* parent )
: QDialog( parent )
, ui( new Ui::MyProgram )
{
ui->setupUi( this );
QStringList allFiles = QDir( "~/" ).entryList( QStringList << "*.txt" );
for( int cont = 0; cont < allFiles.size(); ++cont )
{
bool ok = true;
try {
//try something
} catch( //exception )
{
ok = false;
}
if (ok) {
//insert values in my QTableWidget
}
}
}
How I can add a row in a QTableWidget without knowing how many items this will have?
This works:
MyProgram::MyProgram( QWidget* parent )
: QDialog( parent )
, ui( new Ui::MyProgram )
{
ui->setupUi( this );
QStringList allFiles = QDir( "~/" ).entryList( QStringList << "*.txt" );
for( int cont = 0; cont < allFiles.size(); ++cont )
{
bool ok = true;
try {
//try something
} catch( //exception )
{
ok = false;
}
if (ok) {
int row = ui->myQTableWidget->rowCount();
ui->myQTableWidget->insertRow( row );
// setItems
}
}
}
Related
I'm reading a ~2 MB json file to a QAbstractItemModel visualised by a QTreeView. Each json object converts to a row in the model. The program consumes +700 MB in memory. This ratio of storage space and memory usage is not very satisfying.
I assume, the QAbstractItemModel is responsible:
Using a very small json file, memory consumption drops to ~50 MB.
Disabling the views setModel function does not change the memory consumption significantly.
Is this the behavior to be expected? I assume not.
Is there a way to optimise the memory usage? I assume this should be handled in the models data item realisation. I attached my RowItem realisation in the following:
.h file:
class RowItem
{
public:
explicit RowItem();
virtual ~RowItem();
void setParent( RowItem * p_pParent );
void appendChild( RowItem * p_pChild );
void insertChild( int p_nRow, RowItem * p_pChild );
bool removeChild(int p_nRow);
bool replaceChild(RowItem * p_pOldChild , RowItem *p_pNewChild);
RowItem * child( int p_nRow ) const;
int rowCount() const;
int columnCount() const;
int column( const QVariant & p_grData, int p_nRole = Qt::DisplayRole ) const;
QVariant data(const int & p_nColumn, int p_nRole = Qt::DisplayRole ) const;
int row() const;
RowItem * parentItem();
bool setData( const int & p_nColumn, const QVariant & p_grData, int p_nRole = Qt::DisplayRole );
RowItem & operator=( RowItem & pSrc );
protected:
QList< RowItem * > m_pChildItems;
QList< QMap< quint8, QVariant > > m_grColList; /// #attention List index = column; value map: quint8 = p_nRole ( e.g. Qt::DisplayRole, limited to max 256), QVarinat = data
RowItem * m_pParentItem;
};
.cpp file
RowItem::RowItem() : m_pParentItem( nullptr )
{
}
RowItem::~RowItem()
{
qDeleteAll(m_pChildItems );
}
void RowItem::setParent(RowItem *p_pParent)
{
m_pParentItem = p_pParent;
}
void RowItem::appendChild(RowItem *p_pChild)
{
m_pChildItems.append(p_pChild);
p_pChild->setParent( this );
}
void RowItem::insertChild(int p_nRow, RowItem *p_pChild)
{
m_pChildItems.insert( p_nRow, p_pChild );
p_pChild->setParent( this );
}
bool RowItem::removeChild(int p_nRow )
{
if ( m_pChildItems.size() <= p_nRow ) {
return false;
}
RowItem * pChild = m_pChildItems.at( p_nRow );
delete pChild;
pChild = nullptr;
m_pChildItems.removeAt( p_nRow );
return true;
}
bool RowItem::replaceChild(RowItem * p_pOldChild, RowItem * p_pNewChild )
{
if ( ( p_pOldChild == nullptr ) || ( p_pNewChild == nullptr ) ) {
return false;
}
int nIdx = m_pChildItems.indexOf( p_pOldChild );
if ( nIdx == -1 ) {
return false;
}
m_pChildItems.replace( nIdx, p_pNewChild );
p_pNewChild->setParent( this );
return true;
}
RowItem *RowItem::child(int p_nRow) const
{
if ( ( p_nRow >= m_pChildItems.size() ) || ( p_nRow < 0 ) )
{
QLOG_ERROR() << "Requested child item not existent. m_pChildItems.size() = " << m_pChildItems.size() << "; requested item:" << p_nRow << Q_FUNC_INFO;
return nullptr;
}
return m_pChildItems.at(p_nRow);
}
int RowItem::rowCount() const
{
return m_pChildItems.count();
}
int RowItem::columnCount() const
{
return m_grColList.count();
}
int RowItem::column(const QVariant &p_grData, int /*p_nRole*/) const
{
for( int i = 0; i < m_grColList.size(); ++i ) {
const QMap< quint8, QVariant > & grRoleMap = m_grColList.at( i );
if( grRoleMap.values().contains( p_grData ) == true ) {
return i;
}
}
return -1;
}
QVariant RowItem::data(const int &p_nColumn, int p_nRole) const
{
if ( ( p_nColumn < 0 ) || ( p_nRole < 0 ) ) {
QLOG_ERROR() << "Requested invalid column or role data:" << p_nColumn << p_nRole << Q_FUNC_INFO;
return QVariant();
}
if ( m_grColList.size() <= p_nColumn ) {
QLOG_ERROR() << "Requested column does not exists. Column size is " << m_grColList.size() << "; requested was col" << p_nColumn << Q_FUNC_INFO;
return QVariant();
}
const QMap< quint8, QVariant > & grRoleMap = m_grColList.at( p_nColumn );
QVariant grValue = grRoleMap.value( p_nRole, QVariant() );
if ( ( p_nRole == Qt::EditRole ) && ( ! grValue.isValid() ) ) {
grValue = grRoleMap.value( Qt::DisplayRole, QVariant() );
}
return grValue;
}
int RowItem::row() const
{
int nRow = 0;
if ( m_pParentItem != nullptr ) {
nRow = m_pParentItem->m_pChildItems.indexOf( const_cast< RowItem* >( this ) );
}
return nRow;
}
RowItem *RowItem::parentItem()
{
return m_pParentItem;
}
bool RowItem::setData( const int & p_nColumn, const QVariant &p_grData , int p_nRole)
{
QMap< quint8 , QVariant > grRoleMap;
int nCol = p_nColumn;
if ( p_nColumn == -1 ) {
m_grColList.append( QMap< quint8 , QVariant >() );
nCol = m_grColList.size() - 1;
}
else {
// expand coloumns if required
while( m_grColList.size() <= p_nColumn ) {
m_grColList.append( QMap< quint8 , QVariant >() );
}
grRoleMap = m_grColList.at( p_nColumn );
}
grRoleMap.insert( p_nRole, p_grData );
m_grColList.replace( nCol, grRoleMap );
return true;
}
RowItem &RowItem::operator=(RowItem &p_grSrc)
{
m_grColList = p_grSrc.m_grColList;
return * this;
}
I have a QStandardItemModel, which I display in q QTreeView. Works fine.
To highlight relevant rows I want to highlight some of them: Therefore I have a QStringList with the names of the QStandItem* s to be highlighted.
QStringList namesToBeHighlighted = getNames();
QModelIndex in = myModel->index(0, 0);
if ( in.isValid() ) {
for (int curIndex = 0; curIndex < myModel->rowCount(in); ++curIndex) {
QModelIndex si = myModel->index(curIndex, 0, in);
QStandardItem *curItem = myModel->itemFromIndex(si);
if (curItem) {
QString curItemName = curItem->text();
if ( namesToBeHighlighted.contains(curItem->text()) ) {
curItem->setFont(highlightFont);
}
else curItem->setFont(unHighlightFont);
}
}
}
My Model has following structure:
Level_1
+--> Level_11
+--> Level_12
+--> Level_13
Level_2
+--> Level_21
+--> Level_22
+--> Level_23
...
Here, it iterates trough Levels 11, 12 and 13 then it stops.
I hope it helps you:
void forEach(QAbstractItemModel* model, QModelIndex parent = QModelIndex()) {
for(int r = 0; r < model->rowCount(parent); ++r) {
QModelIndex index = model->index(r, 0, parent);
QVariant name = model->data(index);
qDebug() << name;
// here is your applicable code
if( model->hasChildren(index) ) {
forEach(model, index);
}
}
}
QStandardItemModel model;
QStandardItem* parentItem = model.invisibleRootItem();
for (int i = 0; i < 4; ++i) {
QStandardItem *item = new QStandardItem(QString("item %0").arg(i));
for (int j = 0; j < 5; ++j) {
item->appendRow(new QStandardItem(QString("item %0%1").arg(i).arg(j)));
}
parentItem->appendRow(item);
parentItem = item;
}
forEach(&model);
info:
We are trying to create a property whose sub properties may be added/removed depending on the value of another sub property.
An example of this could be an plant object. This object has one property which will be a drop down consisting of types of plants, lets say (daisy, daffodil, and venus fly trap). If venus is selected, I would like to have a property show up below called avgFlyIntake but if daffodil is selected this property should disappear.
example:
Plant
type venus
avgFlyI 2.0
avgHight 3.0
Or
Plant
type daffodil
avgHight 8.0
//Fly Property gone or grayed out.
Edit: Essentially plant is a property of another model that I guess could be called livingThing. The property's show up in a hierarchical fashion in a 2 column table. I'd like the plant properties to be dynamically hidden if it is possible.
c++ src:
PlantProperty::PlantProperty(const QString& name /*= QString()*/, QObject* propertyObject /*= 0*/, QObject* parent /*= 0*/)
: Property(name, propertyObject, parent)
{
m_type = new Property("id", this, this);
m_avgFlyIntake = new Property("avgFlyIntake", this, this);
m_avgHeight = new Property("avgHeight", this, this);
//setEditorHints("...");
}
enum PlantProperty::getType() const{
return value().value<Plant>().getType();
}
void PlantProperty::setType(enum enabled){
//if enum changed show and hide relevant properties associated with selection
Property::setValue(QVariant::fromValue(Plant(...)));
}
c++ h:
class PlantProperty : public Property{
Q_OBJECT
/**/
Q_PROPERTY(int type READ getType WRITE setType DESIGNABLE true USER true)
Q_PROPERTY(float avgFlyIntake READ getavgFlyIntake WRITE setAvgFlyIntake DESIGNABLE true USER ture)
Q_PROPERTY(float avgHeight READ getavgHeight WRITE setavgHeihgt DESIGNABLE true USER true)
public:
PlantProperty (const QString&name = QString(), QObject* propertyObject = 0, QObject* parent = 0);
QVariant data(const QModelIndex &index, int role) const;
int rowCount(const QModelIndex &parent = QModelIndex()) const;
QVariant value(int role = Qt::UserRole) const;
virtual void setValue(const QVariant& value);
void setEditorHints(const QString& hints);
int getType() const;
void setType(int id);
private:
QString parseHints(const QString& hints, const QChar component);
Property* type;
Property* avgFlyIntake;
Property* avgHeight;
};
Q_DECLARE_METATYPE(Plant)
#endif //PLANTPROPERTY_H
q property model:
// *************************************************************************************************
//
// QPropertyEditor v 0.3
//
// --------------------------------------
// Copyright (C) 2007 Volker Wiendl
// Acknowledgements to Roman alias banal from qt-apps.org for the Enum enhancement
//
//
// The QPropertyEditor Library is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation version 3 of the License
//
// The Horde3D Scene Editor is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
// *************************************************************************************************
#include "QPropertyModel.h"
#include "Property.h"
#include "EnumProperty.h"
#include <QtGui/QApplication>
#include <QtCore/QMetaProperty>
#include <QtGui/QItemEditorFactory>
struct PropertyPair
{
PropertyPair(const QMetaObject* obj, QMetaProperty property) : Property(property), Object(obj) {}
QMetaProperty Property;
const QMetaObject* Object;
bool operator==(const PropertyPair& other) const {return QString(other.Property.name()) == QString(Property.name());}
};
QPropertyModel::QPropertyModel(QObject* parent /*= 0*/) : QAbstractItemModel(parent)
{
m_rootItem = new Property("Root",0, this);
}
QPropertyModel::~QPropertyModel()
{
}
QModelIndex QPropertyModel::index ( int row, int column, const QModelIndex & parent /*= QModelIndex()*/ ) const
{
Property *parentItem = m_rootItem;
if (parent.isValid())
parentItem = static_cast<Property*>(parent.internalPointer());
if (row >= parentItem->children().size() || row < 0)
return QModelIndex();
return createIndex(row, column, parentItem->children().at(row));
}
QModelIndex QPropertyModel::parent ( const QModelIndex & index ) const
{
if (!index.isValid())
return QModelIndex();
Property *childItem = static_cast<Property*>(index.internalPointer());
Property *parentItem = qobject_cast<Property*>(childItem->parent());
if (!parentItem || parentItem == m_rootItem)
return QModelIndex();
return createIndex(parentItem->row(), 0, parentItem);
}
int QPropertyModel::rowCount ( const QModelIndex & parent /*= QModelIndex()*/ ) const
{
Property *parentItem = m_rootItem;
if (parent.isValid())
parentItem = static_cast<Property*>(parent.internalPointer());
return parentItem->children().size();
}
int QPropertyModel::columnCount ( const QModelIndex & /*parent = QModelIndex()*/ ) const
{
return 2;
}
QVariant QPropertyModel::data ( const QModelIndex & index, int role /*= Qt::DisplayRole*/ ) const
{
if (!index.isValid())
return QVariant();
Property *item = static_cast<Property*>(index.internalPointer());
switch(role)
{
case Qt::ToolTipRole:
case Qt::DecorationRole:
case Qt::DisplayRole:
case Qt::EditRole:
if (index.column() == 0)
return item->objectName().replace('_', ' ');
if (index.column() == 1)
return item->value(role);
case Qt::BackgroundRole:
if (item->isRoot()) return QApplication::palette("QTreeView").brush(QPalette::Normal, QPalette::Button).color();
break;
};
return QVariant();
}
// edit methods
bool QPropertyModel::setData ( const QModelIndex & index, const QVariant & value, int role /*= Qt::EditRole*/ )
{
if (index.isValid() && role == Qt::EditRole)
{
Property *item = static_cast<Property*>(index.internalPointer());
item->setValue(value);
emit dataChanged(index, index);
return true;
}
return false;
}
Qt::ItemFlags QPropertyModel::flags ( const QModelIndex & index ) const
{
if (!index.isValid())
return Qt::ItemIsEnabled;
Property *item = static_cast<Property*>(index.internalPointer());
// only allow change of value attribute
if (item->isRoot())
return Qt::ItemIsEnabled;
else if (item->isReadOnly())
return Qt::ItemIsDragEnabled | Qt::ItemIsSelectable;
else
return Qt::ItemIsDragEnabled | Qt::ItemIsEnabled | Qt::ItemIsSelectable | Qt::ItemIsEditable;
}
QVariant QPropertyModel::headerData ( int section, Qt::Orientation orientation, int role /*= Qt::DisplayRole*/ ) const
{
if (orientation == Qt::Horizontal && role == Qt::DisplayRole)
{
switch (section)
{
case 0:
return tr("Name");
case 1:
return tr("Value");
}
}
return QVariant();
}
QModelIndex QPropertyModel::buddy ( const QModelIndex & index ) const
{
if (index.isValid() && index.column() == 0)
return createIndex(index.row(), 1, index.internalPointer());
return index;
}
void QPropertyModel::addItem(QObject *propertyObject)
{
// first create property <-> class hierarchy
QList<PropertyPair> propertyMap;
QList<const QMetaObject*> classList;
const QMetaObject* metaObject = propertyObject->metaObject();
do
{
int count = metaObject->propertyCount();
for (int i=0; i<count; ++i)
{
QMetaProperty property = metaObject->property(i);
if( property.isUser() ) // Hide Qt specific properties
{
PropertyPair pair(metaObject, property);
int index = propertyMap.indexOf(pair);
if (index != -1)
propertyMap[index] = pair;
else
propertyMap.push_back(pair);
}
}
classList.push_front(metaObject);
}
while ((metaObject = metaObject->superClass())!=0);
QList<const QMetaObject*> finalClassList;
// remove empty classes from hierarchy list
foreach(const QMetaObject* obj, classList)
{
bool keep = false;
foreach(PropertyPair pair, propertyMap)
{
if (pair.Object == obj)
{
keep = true;
break;
}
}
if (keep)
finalClassList.push_back(obj);
}
// finally insert properties for classes containing them
int i=rowCount();
Property* propertyItem = 0;
beginInsertRows( QModelIndex(), i, i + finalClassList.count() );
foreach(const QMetaObject* metaObject, finalClassList)
{
// Set default name of the hierarchy property to the class name
QString name = metaObject->className();
// Check if there is a special name for the class
int index = metaObject->indexOfClassInfo(qPrintable(name));
if (index != -1)
name = metaObject->classInfo(index).value();
// Create Property Item for class node
propertyItem = new Property(name, 0, m_rootItem);
foreach(PropertyPair pair, propertyMap)
{
// Check if the property is associated with the current class from the finalClassList
if (pair.Object == metaObject)
{
QMetaProperty property(pair.Property);
Property* p = 0;
if (property.type() == QVariant::UserType && !m_userCallbacks.isEmpty())
{
QList<QPropertyEditorWidget::UserTypeCB>::iterator iter = m_userCallbacks.begin();
while( p == 0 && iter != m_userCallbacks.end() )
{
p = (*iter)(property.name(), propertyObject, propertyItem);
++iter;
}
}
if( p == 0){
if(property.isEnumType()){
p = new EnumProperty(property.name(), propertyObject, propertyItem);
} else {
p = new Property(property.name(), propertyObject, propertyItem);
}
}
int index = metaObject->indexOfClassInfo(property.name());
if (index != -1)
p->setEditorHints(metaObject->classInfo(index).value());
}
}
}
endInsertRows();
if( propertyItem ) addDynamicProperties( propertyItem, propertyObject );
}
void QPropertyModel::updateItem ( QObject* propertyObject, const QModelIndex& parent /*= QModelIndex() */ )
{
Property *parentItem = m_rootItem;
if (parent.isValid())
parentItem = static_cast<Property*>(parent.internalPointer());
if (parentItem->propertyObject() != propertyObject)
parentItem = parentItem->findPropertyObject(propertyObject);
if (parentItem) // Indicate view that the data for the indices have changed
{
QModelIndex itemIndex = createIndex(parentItem->row(), 0, static_cast<Property*>(parentItem));
dataChanged(itemIndex, createIndex(parentItem->row(), 1, static_cast<Property*>(parentItem)));
QList<QByteArray> dynamicProperties = propertyObject->dynamicPropertyNames();
QList<QObject*> childs = parentItem->parent()->children();
int removed = 0;
for(int i = 0; i < childs.count(); ++i )
{
QObject* obj = childs[i];
if( !obj->property("__Dynamic").toBool() || dynamicProperties.contains( obj->objectName().toLocal8Bit() ) )
continue;
beginRemoveRows(itemIndex.parent(), i - removed, i - removed);
++removed;
delete obj;
endRemoveRows();
}
addDynamicProperties(static_cast<Property*>(parentItem->parent()), propertyObject);
}
}
void QPropertyModel::addDynamicProperties( Property* parent, QObject* propertyObject )
{
// Get dynamic property names
QList<QByteArray> dynamicProperties = propertyObject->dynamicPropertyNames();
QList<QObject*> childs = parent->children();
// Remove already existing properties from list
for(int i = 0; i < childs.count(); ++i )
{
if( !childs[i]->property("__Dynamic").toBool() ) continue;
int index = dynamicProperties.indexOf( childs[i]->objectName().toLocal8Bit() );
if( index != -1)
{
dynamicProperties.removeAt(index);
continue;
}
}
// Remove invalid properites and those we don't want to add
for(int i = 0; i < dynamicProperties.size(); ++i )
{
QString dynProp = dynamicProperties[i];
// Skip properties starting with _ (because there may be dynamic properties from Qt with _q_ and we may
// have user defined hidden properties starting with _ too
if( dynProp.startsWith("_") || !propertyObject->property( qPrintable(dynProp) ).isValid() )
{
dynamicProperties.removeAt(i);
--i;
}
}
if( dynamicProperties.empty() ) return;
QModelIndex parentIndex = createIndex(parent->row(), 0, static_cast<Property*>(parent));
int rows = rowCount(parentIndex);
beginInsertRows(parentIndex, rows, rows + dynamicProperties.count() - 1 );
// Add properties left in the list
foreach(QByteArray dynProp, dynamicProperties )
{
QVariant v = propertyObject->property(dynProp);
Property* p = 0;
if( v.type() == QVariant::UserType && !m_userCallbacks.isEmpty() )
{
QList<QPropertyEditorWidget::UserTypeCB>::iterator iter = m_userCallbacks.begin();
while( p == 0 && iter != m_userCallbacks.end() )
{
p = (*iter)(dynProp, propertyObject, parent);
++iter;
}
}
if( p == 0 ) p = new Property(dynProp, propertyObject, parent);
p->setProperty("__Dynamic", true);
}
endInsertRows();
}
void QPropertyModel::clear()
{
beginRemoveRows(QModelIndex(), 0, rowCount());
delete m_rootItem;
m_rootItem = new Property("Root",0, this);
endRemoveRows();
}
void QPropertyModel::registerCustomPropertyCB(QPropertyEditorWidget::UserTypeCB callback)
{
if ( !m_userCallbacks.contains(callback) )
m_userCallbacks.push_back(callback);
}
void QPropertyModel::unregisterCustomPropertyCB(QPropertyEditorWidget::UserTypeCB callback)
{
int index = m_userCallbacks.indexOf(callback);
if( index != -1 )
m_userCallbacks.removeAt(index);
}
QObject has a dynamic property system, so you do not need to manually declare any properties at all. It'd be easy to map such objects to an item view. But it seems like the use of a QObject is overkill.
It seems like you'd be completely covered by using a QStandardItemModel and its items, arranged in a tree. An item could be either a plant, or a plant's property.
i have problem with QStandardItemModel. I want to get values from one model (id, name, parent) and build tree in another model.
First i'm getting all childrens of any parent to QMultiMap<int,QStandardItem*> childrenIndexes:
getChildrens()
{
for(int i = 0 ; i < tableModel->rowCount() ; i++ )
{
QStandardItem* item_ptr = tableModel->item(i,1);
int parent;
if(tableModel->item(i,2)->text() == "null")
{
parent = -1;
}
else
{
parent = tableModel->item(i,2)->text().toInt();
}
childrenIndexes.insert(parent, item_ptr);
}
}
Multimap builds fine, in next step i recursively call building function. Starting from root (Item 1):
void addChildrens(QStandardItem* item)
{
int id = tableModel->item(tableModel->indexFromItem(item).row(),0)->text().toInt();
QString name = tableModel->item(tableModel->indexFromItem(item).row(),1)->text();
qDebug() << "Parsing item: " << name;
int parent;
if(tableModel->item(tableModel->indexFromItem(item).row(),2)->text() == "null")
{
qDebug() << "Got root!";
item = new QStandardItem(name);
treeModel->appendRow(item);
parent = -1;
}
else
{
parent = tableModel->item(tableModel->indexFromItem(item).row(),2)->text().toInt();
}
qDebug("Got %d childrens!",childrenIndexes.values(id).count());
for(int i = 0 ; i < childrenIndexes.values(id).count() ; i++)
{
QStandardItem* newItem = childrenIndexes.values(id).at(i);
qDebug() << newItem->text();
item->appendRow(newItem->clone());
addChildrens(newItem);
}
}
Unfortunately my tree got only childrens of root. Where is problem?
I am developing a Qt application using QTreeView and QFileSystemModel.
I am able to get the parent's child till one level but I am not able to get the parent's child's child.
For eg:
C is child of B,
B is child of A
I am able to get B as A's child but I also want C as A's Child.
I want like this C->B->A.
Can someone give some input regarding this and help me out.
Thanks in advance.
//QItemSelectionModel *sel = ui->dir_tree->selectionModel();
QStringList strings = extractStringsFromModel(ui->dir_tree->model(), ui->dir_tree->rootIndex());
QFileSystemModel* model = (QFileSystemModel*)ui->dir_tree->model();
QModelIndexList indexlist = ui->dir_tree->selectionModel()->selectedIndexes();
QVariant data;
//QList<QModelIndex> modelindex(indexlist);
int row = -1;
for(int i=0; i<indexlist.size();i=i+4)
{
QModelIndex mi=indexlist.at(i);
info1 = model->fileInfo(mi);
QString childstr = info1.filePath();
QString childname = info1.fileName();
QModelIndex mi2= indexlist.at(i).parent();
info = model->fileInfo(mi2);
QString parentstr = info.filePath();
QString parentname = info.fileName();
QStringList childlist;
for(int j=0;j<model->rowCount(indexlist.at(i));j++)
{
QModelIndex mi3 = indexlist.at(i).child(j, 0);
info2 = model->fileInfo(mi3);
QString childrenstr = info2.filePath();
childlist << childrenstr;
qDebug()<<"parents' children"<<childrenstr<<j;
}
}
I like to use recursion for this kind of thing:
void MyTreeView::GetAllChildren(QModelIndex &index, QModelIndexList &indicies)
{
indicies.push_back(index);
for (int i = 0; i != model()->rowCount(index); ++i)
GetAllChildren(index.child(i,0), indicies);
}
Usage (from somewhere inside the tree view):
QModelIndexList list;
GetAllChildren(model()->index(0,0), list);
Getting all children breadth-first:
QModelIndexList children;
// Get top-level first.
for ( int i = 0; i < model->rowCount(); ++i ) {
children << model->index( i, 0 ); // Use whatever column you are interested in.
}
// Now descend through the generations.
for ( int i = 0; i < children.size(); ++i ) {
for ( int j = 0; j < model->rowCount( children[i] ); ++j ) {
children << children[i].child( j, 0 );
}
}
Getting all parents from a child:
QModelIndexList parents;
parents << child.parent();
while ( parents.last().isValid() ) {
parents << parents.last().parent();
}
Please note, I haven't tried these samples!
//Delete
QList<QTreeWidgetItem *> selected = ui->twg->selectedItems();
QTreeWidgetItem *item = selected.first();
QTreeWidgetItem *parent = item->parent();
if(parent) {
int index = parent->indexOfChild(item);
delete parent->takeChild(index);
}
//Add
QList<QTreeWidgetItem *> selected = ui->twg->selectedItems();
QTreeWidgetItem *item = selected.first();
QTreeWidgetItem *parent = item->parent();
if(parent) {
QTreeWidgetItem *tmp = new QTreeWidgetItem(parent);
tmp->setText(0, "Dude");
parent->addChild(tmp);
}