首页 > 解决方案 > QFileDialog 中的工具提示(或其他操作)

问题描述

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

标签: qtqfiledialogqtwidgets

解决方案


我不确定是否有任何批准/确定的方式来做到这一点。以下是实现您想要的(我认为)的一种相当老套的方法,但它对与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();
}

推荐阅读