Parcourir la source

ctkPythonConsole - Autocompleter - Add parenthesis if it applies

Jean-Christophe Fillion-Robin il y a 14 ans
Parent
commit
2322058ddd

+ 9 - 3
Libs/Scripting/Python/Core/ctkAbstractPythonManager.cpp

@@ -174,7 +174,8 @@ void ctkAbstractPythonManager::setInitializationFunction(void (*initFunction)())
 
 //----------------------------------------------------------------------------
 QStringList ctkAbstractPythonManager::pythonAttributes(const QString& pythonVariableName,
-                                                       const QString& module) const
+                                                       const QString& module,
+                                                       bool appendParenthesis) const
 {
   Q_ASSERT(PyThreadState_GET()->interp);
   PyObject* dict = PyImport_GetModuleDict();
@@ -245,8 +246,13 @@ QStringList ctkAbstractPythonManager::pythonAttributes(const QString& pythonVari
           {
           continue;
           }
-
-        results << PyString_AsString(key);
+        QString key_str(PyString_AsString(key));
+        // Append "()" if the associated object is a function
+        if (appendParenthesis && PyCallable_Check(value))
+          {
+          key_str.append("()");
+          }
+        results << key_str;
         Py_DECREF(value);
         }
       Py_DECREF(keys);

+ 5 - 2
Libs/Scripting/Python/Core/ctkAbstractPythonManager.h

@@ -62,9 +62,12 @@ public:
   void setInitializationFunction(void (*initFunction)());
 
   /// Given a python variable name, lookup its attributes and return them in a string list.
-  /// \note By default the attributes are looked up from __main__
+  /// By default the attributes are looked up from \c __main__.
+  /// If the argument \c appendParenthesis is set to True, "()" will be appended to attributes
+  /// being Python callable.
   QStringList pythonAttributes(const QString& pythonVariableName,
-                               const QString& module = QLatin1String("__main__")) const;
+                               const QString& module = QLatin1String("__main__"),
+                               bool appendParenthesis = false) const;
 
 signals:
 

+ 4 - 2
Libs/Scripting/Python/Widgets/ctkPythonConsole.cpp

@@ -127,8 +127,10 @@ public:
     QStringList attrs;
     if (!lookup.isEmpty() || !compareText.isEmpty())
       {
-      attrs = this->PythonManager.pythonAttributes(lookup, QLatin1String("__main__"));
-      attrs << this->PythonManager.pythonAttributes(lookup, QLatin1String("__main__.__builtins__"));
+      bool appendParenthesis = true;
+      attrs = this->PythonManager.pythonAttributes(lookup, QLatin1String("__main__"), appendParenthesis);
+      attrs << this->PythonManager.pythonAttributes(lookup, QLatin1String("__main__.__builtins__"),
+                                                    appendParenthesis);
       attrs.removeDuplicates();
       }