开发者

Detecting missing resources in QT Stylesheets

开发者 https://www.devze.com 2023-01-19 04:50 出处:网络
I am using QCSS stylesheets in QT to skin several buttons with images from the QT resource system: QFrame#DialogButtonTitle_SaveAsNew

I am using QCSS stylesheets in QT to skin several buttons with images from the QT resource system:

QFrame#DialogButtonTitle_SaveAsNew
{
  background-image: url(images:DialogButtonTitle_SaveAsNew.png);
}

This works great, but I would really like to write a warning to our logs if the image file referenced from the CSS could not be found (and the button is thus na开发者_开发百科ked). Any way to catch such errors?


I believe you can do it like this:

  • Read about the QAbstractFileEngine and QAbstractFileEngineHandler classes.
  • Extend Qt's own implementation, QFSFileEngine. I believe it also handles the ":" namespace.
  • Reimplement the QAbstractFileEngine::open() method.
  • Register your engine using a custom QAbstractFileEngineHandler. The create() method should check the file name to see if it is being read from a resource file.

Haven't tested, but I think it should work. Code:

bool MyEngine::open(QIODevice::OpenMode mode)
{
    bool r = QFSFileEngine::open(mode);
    if (!r) {
        qWarning() << "Failed to open" << fileName();
    }
    return r;
}

QAbstractFileEngine *MyEngineHandler::create(const QString &fileName) const
{
     return fileName.startsWith("images:") ? new MyEngine(fileName) : 0;
}

Edit.

This will not work. The resource file system, “:”, is handled by a private file engine called QResourceFileEngine, not by QFSFileEngine.


Based on @andref answer, I came up with this, which works for me (TM):

class LoggingEngineHandler : public QAbstractFileEngineHandler
{
public:
  LoggingEngineHandler()
  : QAbstractFileEngineHandler()
  , m_lookUpInProgress(false)
  , m_lookUpPaths(QRegExp("^(images|meshes|app|sounds):"))
  {
    // empty
  }

  QAbstractFileEngine* create(const QString &fileName) const override
  {
    if (!fileName.contains(m_lookUpPaths))
      return 0;

    if (m_lookUpInProgress)
      return 0;

    m_lookUpInProgress = true;
    QFileInfo info = QFileInfo(fileName);
    m_lookUpInProgress = false;

    if (!info.exists())
    {
      assert(!Utilities::isRunByUser("designer"));
      LOG_WARN("Required resource file does not exist: %1%", QUtil_s(fileName));
    }

    return 0;
  }
protected:
  mutable bool m_lookUpInProgress;

  QRegExp m_lookUpPaths;
};


It's possible that Qt will call one of their message functions when something like this happens (although I don't know for sure). If it does, you could install a message handler function and append some or all of the messages to your log file. There is some information about doing so in the documentation for qInstallMsgHandler.

0

精彩评论

暂无评论...
验证码 换一张
取 消