【问题标题】:how to use Qt setWindowFilePath如何使用 Qt setWindowFilePath
【发布时间】:2010-08-16 14:14:23
【问题描述】:

我似乎无法让 setWindowFilePath 在我的任何项目中工作。该值已存储并可检索,但它从未出现在我的应用程序的标题栏中。它在我下载的示例应用程序中确实可以正常工作,但我找不到它们的不同之处。无论如何,这是我创建的一个简单的应用程序来演示这个问题。我粘贴了下面 3 个文件 mainwin.h、main.cpp 和 mainwin.cpp 中的代码。

有什么想法吗?我在 Windows 7 上使用带有 MS 编译器的 Qt 4.6.3。

#ifndef MAINWIN_H
#define MAINWIN_H

#include <QMainWindow>

class mainwin : public QMainWindow
{
    Q_OBJECT
public:
    explicit mainwin(QWidget *parent = 0);

signals:

public slots:

};

#endif // MAINWIN_H

#include "mainwin.h"
#include <QApplication>

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);
    app.setApplicationName("my test");
    app.setOrganizationName("NTFMO");
    mainwin window;
    window.show();
    return app.exec();
}

#include "mainwin.h"

mainwin::mainwin(QWidget *parent) :
    QMainWindow(parent)
{
  setWindowFilePath("C:\asdf.txt");

}

【问题讨论】:

    标签: qt qt4 qt4.6


    【解决方案1】:

    QTBUG-16507

    简单的解决方法(刚刚在我的项目中测试过)是:

    /********************** HACK: QTBUG-16507 workaround **************************/
    void MyMainWindow::showEvent(QShowEvent *event)
    {
        QMainWindow::showEvent(event);
        QString file_path = windowFilePath();
        setWindowFilePath(file_path+"wtf we have some random text here");
        setWindowFilePath(file_path);
    }
    /******************************************************************************/
    

    它只会将标题设置为您在小部件显示之前使用的值(在构造函数中,在您的情况下)。像魅力一样工作。

    【讨论】:

    • 似乎该错误已修复。至少我不能在 Qt 5.0.2 中重现它了。
    【解决方案2】:

    由于某种原因,setWindowFilePath() 从 QMainWindow 的构造函数调用时似乎不起作用。但是你可以使用单发计时器:

    class mainwin : public QMainWindow
    {
    ...
    private slots:
        void setTitle();
    }
    
    mainwin::mainwin(QWidget *parent) :
        QMainWindow(parent)
    {
        QTimer::singleShot(0, this, SLOT(setTitle()));
    }
    
    void mainwin::setTitle()
    {
        setWindowFilePath("C:\\asdf.txt");
    }
    

    记住在文字路径中使用 \\ 而不是 \

    【讨论】:

    • 谢谢,成功了!并感谢有关 \\ 而不是 \ 的提醒
    【解决方案3】:

    我刚刚发现使用 QTimer::singleShot,显然没有办法传递参数。要传递参数(在我的例子中,是使用 QSettings 检索的文件路径),请使用:

    QMetaObject::invokeMethod(this, "Open", Qt::QueuedConnection, Q_ARG(QString, last_path));
    

    【讨论】:

      猜你喜欢
      • 2011-06-05
      • 1970-01-01
      • 1970-01-01
      • 2011-05-13
      • 2011-08-14
      • 2018-06-02
      • 1970-01-01
      • 2011-08-10
      • 1970-01-01
      相关资源
      最近更新 更多