我正在尝试将自定义文件与osx应用相关联。我有一个将文件与应用程序关联的plist,但是双击文件会打开应用程序,里面没有数据。
致电
someapp.app/Contents/MacOs/someapp somefile.abc
在应用程序内正确打开文件。
MyApp::MyApp(int& argc, char**argv): QApplication(argc, argv)
{
...
m_MainWindow = new MainWindows();
m_MainWindow->show();
if(argc > 1 && argv[1])
m_MainWindow->openFile(QString(argv[1]);
else
m_MainWindow->showStartupDialog(); // to create a new document
}
搜索我发现我应该以某种方式实施QFileOpenEvent ......怎么样? 这个example看起来不错......但我不明白如何组合构造函数和事件......
我如何使这项工作?
(OS X 10.6-10.9,使用Qt 4.8创建的应用程序)
答案 0 :(得分:3)
以下是经过修改的代码,它将在开始或正常运行期间响应OpenFileEvent
- 并允许从命令行打开o文件或创建新文件
MyApp::MyApp(int& argc, char**argv): QApplication(argc, argv)
{
...
m_MainWindow = new MainWindows();
m_MainWindow->show();
if(argc > 1 && argv[1])
m_MainWindow->openFile(QString(argv[1]);
else if (m_macFileOpenOnStart != "")
m_MainWindow->openFile(m_macFileOpenOnStart); // open file on start if it exists
else
m_MainWindow->showStartupDialog(); // to create a new document
}
// responds to FileOpenEvent specific for mac
bool MyApp::event(QEvent *event)
{
switch(event->type())
{
case QEvent::FileOpen:
{
QFileOpenEvent * fileOpenEvent = static_cast<QFileOpenEvent *>(event);
if(fileOpenEvent)
{
m_macFileOpenOnStart = fileOpenEvent->file();
if(!m_macFileOpenOnStart.isEmpty())
{
if (m_MainWindow)
{
m_MainWindow->openFile(m_macFileOpenOnStart); // open file in existing window
}
return true;
}
}
}
default:
return QApplication::event(event);
}
return QApplication::event(event);
}
答案 1 :(得分:0)
我使用的QApplication派生类在文件准备就绪时发出信号:
#ifndef OPENWITHAPPLICATION_H
#define OPENWITHAPPLICATION_H
#include <QApplication>
#include <QFileOpenEvent>
#include <QMessageBox>
class OpenWithApplication : public QApplication
{
Q_OBJECT
public:
QString fileName;
OpenWithApplication(int &argc, char **argv)
: QApplication(argc, argv)
{
}
signals:
void fileReady(QString fn);
protected:
bool event(QEvent *event)
{
if (event->type() == QEvent::FileOpen) {
QFileOpenEvent *openEvent = static_cast<QFileOpenEvent *>(event);
fileName = openEvent->file();
emit fileReady(fileName); // the file is ready
}
return QApplication::event(event);
}
};
#endif // OPENWITHAPPLICATION_H
main.cpp将创建的OpenWindowApplication与MainWindow对象连接起来,因此一旦文件准备就绪,信号就会被发出并接收以进行处理
#include "mainwindow.h"
#include <openwithapplication.h>
int main(int argc, char *argv[])
{
OpenWithApplication a(argc, argv);
MainWindow w;
w.connectOpenWithApp(&a);
w.show();
return a.exec();
}
和MainWindow将 fileReady 信号与lambda func连接,该函数打开文件并更新小部件
void MainWindow::connectOpenWithApp(OpenWithApplication*app) {
connect(app, &OpenWithApplication::fileReady, [this](QString fileName){
bw->open(fileName);
bw->update();
});
}