QLineEdit: Is there an elegant solution to tell multiple QLineEdit widgets apart in event handler?

StackOverflow https://stackoverflow.com/questions/8600205

  •  24-03-2021
  •  | 
  •  

Question

I have multiple QLineEdit widgets on a configuration widget.

When the configuration text is changed I want to store the updated value (there are a few of them so I don't want to pass them in one function call at the end).

I was thinking to connect them to one slot or go through QSignalMapper to one slot.

However I'm having trouble finding an elegant way to tell the QLineEdits apart, I want to know which QLineEdit emitted the signal - since I'm in handler object that implements the logic I can't compare the sender() with the original object.

I can hook them up through QSignalMapper so that my handler gets either int id or QObject* or QWidget* reference to the actual widget that emitted the signal so I can get easily the new text, but I would like to be able to switch on some id to update the correct setting internally.

Is there any elegant way to tag or label Qt objects or widgets?

Was it helpful?

Solution

Dynamic properties allow you to 'tag' extra data at run-time onto any QObject derived class. See the QObject::setProperty documentation.

I personally don't like using dynamic properties as they aren't documented in the header of the class. I prefer to inherit from the class and add a standard property.

OTHER TIPS

You may rewrite your own QLineEdit with a value "int id". And whenever QLineEdit emits a signal, also emit your own signal with parameter "id".

class MyLineEdit : public QLineEdit
{
   Q_OBJECT
   private: int id;
   public:  int getID() { return id; }
            void setID(int _id) { id = _id; }
   signals: void myTextEdited(QString,int);
   slots:   void emitMyTextEdited(QString text) { emit myTextEdited(text,id); }
   public:  MyLineEdit(QWidget *parent = 0) : QLineEdit(parent)
            {
                connect(this,SIGNAL(textEdited(QString)),this,SLOT(emitMyTextEdited(QString)));
            }
};

Here, if you want to emit the textEdited signal with the identity of the object, you can rewrite textEdited signal with your way.

Hook them up through QSignalMapper, with a mapping type of QObject*. You can define something like this as your QObject:

class MyQLineEditData : public QObject {
  Q_OBJECT
public:
  QLineEdit* lineEdit ;
  int id ;
} ;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top