how to use Qt setWindowFilePath

偶尔善良 提交于 2019-12-23 01:12:17

问题


I can't seem to get setWindowFilePath to work in any of my projects. The value is stored and can be retrieved, but it never shows up in the title bar of my app. It does work correctly in a sample app I downloaded, but I can't find what they do differently. Anyway, here's a simple app I created to demonstrate the problem. I pasted the code from the 3 files, mainwin.h, main.cpp, and mainwin.cpp below.

Any ideas? I'm using Qt 4.6.3 on Windows 7, with the MS compiler.

#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");

}

回答1:


For some reason, setWindowFilePath() does not seem to work when called from QMainWindow's constructor. But you can use single shot timer:

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");
}

And remember to use \\ in literal paths instead of \




回答2:


It is QTBUG-16507.

And easy workaround (just tested it in my project) is:

/********************** 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);
}
/******************************************************************************/

It will just set title to value that you used before widget show (in constructor, in your case). Works like a charm.




回答3:


I just discovered that with QTimer::singleShot, apparently there is no way to pass parameters. To pass parameters (in my case, the file path retrieved using QSettings), use:

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


来源:https://stackoverflow.com/questions/3493965/how-to-use-qt-setwindowfilepath

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!