qt5pyqt5qfiledialogqvalidator

How do I attach a QRegexpValidator to QFileDialog if I only want say identifier file names?


The question is pretty straightforward and in the title.

Googling didn't help on this one. How do I get the QFileDialog to use a QValidator on its save name field?

Thanks.


Solution

  • The following is a bit of a kludge but appears to work.

    You can use QObject::findChildren to locate the dialog's QLineEdit child widgets. Assuming there's only one such widget you can then apply the validator to that...

    QFileDialog fd;
    auto children = fd.findChildren<QLineEdit *>();
    if (children.size() == 1) {
    
      /*
       * Apply a validator that forces the user to enter a name
       * beginning with a lower case `a' -- a bit pointless but...
       */
      QRegExpValidator validator(QRegExp("^a"));
    
      /*
       * Apply the validator.
       */
      children.front()->setValidator(&validator);
      fd.exec();
    }
    

    A quick test suggests it appears to work just fine. Like I said though: it does feel like a bit of a kludge.