4

I have an instance of https://qgis.org/pyqgis/master/core/Qgis.html#qgis.core.Qgis.MessageLevel, e.g.

level = Qgis.Info

I want to get a human-readable string like "Info" or "Qgis.Info" from this object.

  • print(level) prints 0
    str(level) returns 0
  • type(level) returns <class 'qgis._core.Qgis.MessageLevel'>

Is there a straightforward way to get a human-readable string representation of the MessageLevel object's level?

I am not looking for an if clause checking the integer value against the known values but if that is all that would be possible, a explanatory and canonical "no" would be a good answer.

1

3 Answers 3

4

As far as I am aware PyQt does not support iteration over names/values of Qt's enum types as you could do with standard python enums.

Instead, you can get information on the enumerator via the staticMetaObject of the class which contains the enum. In this case Qgis.

idx = Qgis.staticMetaObject.indexOfEnumerator(Qgis.MessageLevel.__name__)
name = Qgis.staticMetaObject.enumerator(idx).valueToKey(Qgis.Info)

print(name) # prints 'Info'
2

They are a few functions having displayString in their name to convert an enum item to a "display string".

Like https://api.qgis.org/api/classQgsWkbTypes.html#a74a5669aeb2975d4079656202c5ed5d9

For MessageLevel, there isn't any such function in https://api.qgis.org/api/classQgis.html or other classes, as I could checked.

So no, it's not possible AFAIK with the QGIS API. Maybe someone will come with a deeper core Python function with the inspection module ?

1

With pure Python, you can do introspection and create your own useful translator :

from qgis.core import Qgis

message_levels = {
    getattr(Qgis, i): i for i in dir(Qgis)
    if isinstance(getattr(Qgis, i), Qgis.MessageLevel)
}
# {0: 'Info', 1: 'Warning', 2: 'Critical', 3: 'Success', 4: 'NoLevel'}

So, in your usecase :

from qgis.core import Qgis

level = Qgis.Info
print(message_levels[level])
# >>> Info
4
  • The message_levels can most likely not be sorted, so check this stackoverflow.com/questions/9001509/…
    – Taras
    Commented Nov 2, 2022 at 10:19
  • The question here is about the readable message level, I just created a Python dict that transforms Qgis.MessageLevel into readable text. And the dict works without being sorted. Commented Nov 2, 2022 at 10:26
  • I know ^_^ Maybe it simply did not work in my case
    – Taras
    Commented Nov 2, 2022 at 10:30
  • 1
    sorted levels : {k: message_levels[k] for k in sorted(message_levels)} Commented Nov 2, 2022 at 11:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.