Skip to content
Permalink
Browse files

Fix renaming a virtual field leads to crash (fix #15669)

  • Loading branch information
nyalldawson committed Oct 8, 2016
1 parent 3b9316d commit 3a76708bcb4785f5fe930be0b18396e5fa87031f
@@ -27,6 +27,16 @@ class QgsExpressionFieldBuffer
*/
void removeExpression( int index );

/**
* Renames an expression field at a given index
*
* @param index The index of the expression to change
* @param name New name for field
*
* @note added in 3.0
*/
void renameExpression( int index, const QString& name );

/**
* Changes the expression at a given index
*
@@ -33,6 +33,11 @@ void QgsExpressionFieldBuffer::removeExpression( int index )
mExpressions.removeAt( index );
}

void QgsExpressionFieldBuffer::renameExpression( int index, const QString& name )
{
mExpressions[index].field.setName( name );
}

void QgsExpressionFieldBuffer::updateExpression( int index, const QString& exp )
{
mExpressions[index].cachedExpression = QgsExpression( exp );
@@ -61,6 +61,16 @@ class CORE_EXPORT QgsExpressionFieldBuffer
*/
void removeExpression( int index );

/**
* Renames an expression field at a given index
*
* @param index The index of the expression to change
* @param name New name for field
*
* @note added in 3.0
*/
void renameExpression( int index, const QString& name );

/**
* Changes the expression at a given index
*
@@ -2125,10 +2125,41 @@ void QgsVectorLayer::removeFieldAlias( int attIndex )

bool QgsVectorLayer::renameAttribute( int index, const QString& newName )
{
if ( !mEditBuffer || !mDataProvider )
if ( index < 0 || index >= fields().count() )
return false;

return mEditBuffer->renameAttribute( index, newName );
switch ( mFields.fieldOrigin( index ) )
{
case QgsFields::OriginExpression:
{
if ( mExpressionFieldBuffer )
{
int oi = mFields.fieldOriginIndex( index );
mExpressionFieldBuffer->renameExpression( oi, newName );
updateFields();
return true;
}
else
{
return false;
}
}

case QgsFields::OriginProvider:
case QgsFields::OriginEdit:

if ( !mEditBuffer || !mDataProvider )
return false;

return mEditBuffer->renameAttribute( index, newName );

case QgsFields::OriginJoin:
case QgsFields::OriginUnknown:
return false;

}

return false; // avoid warning
}

void QgsVectorLayer::setFieldAlias( int attIndex, const QString& aliasString )
@@ -1058,6 +1058,16 @@ def checkFieldNames(names):
#layer.undoStack().redo()
#checkFieldNames(['fldint'])

def test_RenameExpressionField(self):
layer = createLayerWithOnePoint()
exp_field_idx = layer.addExpressionField('1+1', QgsField('math_is_hard', QVariant.Int))

#rename and check
self.assertTrue(layer.renameAttribute(exp_field_idx, 'renamed'))
self.assertEqual(layer.fields()[exp_field_idx].name(), 'renamed')
f = next(layer.getFeatures())
self.assertEqual(f.fields()[exp_field_idx].name(), 'renamed')

def test_fields(self):
layer = createLayerWithOnePoint()

0 comments on commit 3a76708

Please sign in to comment.
You can’t perform that action at this time.