QFileDialog 中的工具提示或其他操作

问题描述

我希望在 QFileDialog::getopenFileName 实例中将鼠标悬停在文件时弹出工具提示(或理想情况下,QWidget)。
有没有办法在不继承类的情况下做到这一点?

解决方法

我不确定是否有任何经过批准/确定的方法可以做到这一点。以下是实现(我认为)您想要的东西的一种相当笨拙的方式,但它对与 QFileDialog 实例关联的小部件层次结构做出了某些假设。具体来说,它依赖于这样一个假设,即 QFileDialog 实例所包含的小部件层次结构将包含一个或多个 QAbstractItemView 实例...

#include <iostream>
#include <QAbstractItemView>
#include <QApplication>
#include <QCursor>
#include <QFileDialog>
#include <QToolTip>

int
main (int argc,char **argv)
{
  QApplication app(argc,argv);
  QFileDialog fd;

  /*
   * Further to the comments by @Parisa.H.R,we need to make sure we use a
   * non-native file dialog here otherwise there's no way to get the desired
   * behaviour.
   */
  fd.setOption(QFileDialog::DontUseNativeDialog);

  /*
   * Search the widget hierarchy under the QFileDialog looking for instances of
   * QAbstractItemView or derived classes.
   */
  for (auto *v: fd.findChildren<QAbstractItemView *>()) {
    std::clog << "view = " << v << "(type=" << v->metaObject()->className()
              << ",name=\"" << v->objectName().toStdString() << "\")\n";

    /*
     * Connect the view's entered signal to a lambda which,for the time being,* simply displays a tooltip showing the name of the filesystem item.
     */
    QObject::connect(v,&QAbstractItemView::entered,[](const QModelIndex &index)
                       {
                         QToolTip::showText(QCursor::pos(),index.data(Qt::DisplayRole).toString());
                       });

    /*
     * In order to receive the QAbstractItemView::entered signal mouse tracking
     * must be enabled for the view.
     */
    v->setMouseTracking(true);
  }
  fd.exec();
}