Skip to content


Browse files Browse the repository at this point in the history
Preserve edits for multiline editor when length exceeds field size
Previously when using the multiline option for text edit widgets
the entire contents of the field would be discarded if the entered
value exceeded the maximum length for a string field.

Now the entered string is truncated to the maximum field length.
  • Loading branch information
nyalldawson committed Sep 27, 2016
1 parent 35b3b79 commit 7d8fba8
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 1 deletion.
10 changes: 10 additions & 0 deletions src/gui/editorwidgets/qgstexteditwrapper.cpp
Expand Up @@ -66,9 +66,19 @@ QVariant QgsTextEditWrapper::value() const

QVariant res( v );
if ( field().convertCompatible( res ) )
return res;
else if ( field().type() == QVariant::String && field().length() > 0 )
// for string fields convertCompatible may return false due to field length limit - in this case just truncate
// input rather then discarding it entirely
return QVariant( v.left( field().length() ) );
return QVariant( field().type() );

QWidget* QgsTextEditWrapper::createWidget( QWidget* parent )
Expand Down
32 changes: 31 additions & 1 deletion tests/src/python/
Expand Up @@ -14,10 +14,13 @@

import qgis # NOQA

from qgis.core import QgsMapLayerRegistry, QgsFeature, QgsGeometry, QgsPoint, QgsProject, QgsRelation, QgsVectorLayer, NULL
from qgis.core import (QgsMapLayerRegistry, QgsFeature, QgsGeometry, QgsPoint, QgsProject, QgsRelation, QgsVectorLayer, NULL,
from qgis.gui import QgsEditorWidgetRegistry

from qgis.testing import start_app, unittest
from qgis.PyQt.QtCore import QVariant
from qgis.PyQt.QtWidgets import QTextEdit


Expand Down Expand Up @@ -65,6 +68,33 @@ def test_SetValue(self):
self.doAttributeTest(0, ['value', '123', NULL, NULL])
self.doAttributeTest(1, [NULL, 123, NULL, NULL])

def testStringWithMaxLen(self):
""" tests that text edit wrappers correctly handle string fields with a maximum length """
layer = QgsVectorLayer("none?field=fldint:integer", "layer", "memory")
assert layer.isValid()
layer.dataProvider().addAttributes([QgsField('max', QVariant.String, 'string', 10),
QgsField('nomax', QVariant.String, 'string', 0)])

reg = QgsEditorWidgetRegistry.instance()
config = {'IsMultiline': 'True'}

# first test for field without character limit
editor = QTextEdit()
w = reg.create('TextEdit', layer, 2, config, editor, None)
self.assertEqual(w.value(), 'this_is_a_long_string')

# next test for field with character limit
editor = QTextEdit()
w = reg.create('TextEdit', layer, 1, config, editor, None)

self.assertEqual(w.value(), 'this_is_a_')


def test_ValueMap_representValue(self):
layer = QgsVectorLayer("none?field=number1:integer&field=number2:double&field=text1:string&field=number3:integer&field=number4:double&field=text2:string",
"layer", "memory")
Expand Down

0 comments on commit 7d8fba8

Please sign in to comment.