我使用QtSingleApplication使我的qml应用程序成为单实例应用程序。 但是,我无法在其他窗口前激活应用程序。
我使用来自github的最新QtSingleApplication代码,以下是我的主要方法:
#include <QQmlApplicationEngine>
#include <QApplication>
#include <QtQml>
#include <QtSingleApplication>
int main(int argc, char *argv[])
{
QtSingleApplication app(argc, argv);
if (app.isRunning())
{
// I think I should do something here
return 0;
}
QQmlApplicationEngine engine;
engine.load(QUrl(QStringLiteral("qrc:/qml/main.qml")));
return app.exec();
}
如何实现它或其他方式与qml完美地实现单实例应用程序? 感谢!!!
答案 0 :(得分:2)
不,isRunning()
表示程序已在运行另一个实例,因此该实例应该再次退出。
您需要向正在运行的实例发送消息,并且必须使自己前进。
请参阅https://github.com/qtproject/qt-solutions/blob/master/qtsingleapplication/examples/loader/main.cpp
答案 1 :(得分:0)
main.cpp
QQmlApplicationEngine engine;
QObject* qmlObject = engine.rootObjects().at(0);
WindowsPlatformSpecific wps(qmlObject);
QObject::connect(&app, SIGNAL(messageReceived(const QString&)),
&wps, SLOT(handleMessage(const QString&)));
//////////////////////
void WindowsPlatformSpecific::handleMessage(const QString& message)
{
QObject* pp = this->parent();
QWindow* pWnd = qobject_cast<QWindow*>(pp);
if (!pWnd)
qInfo() <<"The winId is null";
WId winId = pWnd->winId();
SetForegroundWindowByWId(winId);
}
/////////////////////////
bool WindowsPlatformSpecific::SetForegroundWindowByWId(WId winId)
{
HWND hWnd = (HWND)winId;
if ( hWnd )
{
ShowWindow(hWnd, SW_SHOWNORMAL);
WINDOWINFO wi;
GetWindowInfo(hWnd, &wi);
bool bTopMost = ((wi.dwExStyle & WS_EX_TOPMOST) == WS_EX_TOPMOST);
SetWindowPos(hWnd, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOSIZE | SWP_NOMOVE);
if (!bTopMost)
{
SetWindowPos(hWnd, HWND_NOTOPMOST, 0, 0, 0, 0, SWP_NOSIZE | SWP_NOMOVE);
}
SetForegroundWindow(hWnd);
return true;
}
return false;
}