QT implements the function of avoiding repeated opening of software

 Because of the needs of the project, I will record it here. Because the QT software we developed will encounter many problems in actual engineering applications. The first is to repeatedly click on the software, which may lead to multiple software pages. For some occasions where the hardware equipment is not good enough, it will aggravate the unsmooth operation of the software, so consider how to avoid this from happening! ! !

Attach the code you implemented here (written directly in the main.cpp file):

First of all, the header file that needs to be added has the following content: the QMessagebox is implemented, and when the repeating software is opened, a software prompt will be given.


#include <QSystemSemaphore>
#include <QSharedMemory>
#include <QMessageBox>

The specific implementation code is as follows:

//避免软件重复打开
    QSystemSemaphore sema("a",1,QSystemSemaphore::Open);
    sema.acquire();// 在临界区操作共享内存   SharedMemory
    QSharedMemory mem("b");// 全局对象名
    if (!mem.create(1))// 如果全局对象以存在则退出
    {
        QMessageBox::information(0, QObject::tr("提示"),QObject::tr(u8"程序运行中,如有需要请先退出"));
        sema.release();
        return 0;
    }
    sema.release();//释放访问的内存

**************************************************************************************************************

For more ways, you can learn about the singleton of Yiha QT;

Singleton is a design pattern that guarantees that there is only one instance of a class and provides a global point of access. In QT, there are several ways to realize singleton:

  • Use a mutex (mutex) to ensure thread safety, that is, add a lock in the method of obtaining an instance to prevent multiple threads from creating an instance at the same time.
  • Use the characteristics of static local variables, that is, define a static local variable in the method of obtaining the instance, it will be initialized at the first call, and it is thread-safe in the C++11 standard.
  • Use the characteristics of static inner classes, that is, define a static inner class in the class, it will be loaded when it is used for the first time, and there is only one instance.
  • Using the characteristics of the enumeration class, that is, using an enumeration type to represent a singleton object, it can avoid thread synchronization problems and prevent deserialization from recreating new objects.
  • Use the std::call_once function of C++11 to implement the singleton mode, which can ensure that a function is called only once and is thread-safe.

For example: Q itself comes with a macro QGLOBALSTATIC, which also has the effect similar to the singleton mode.

Here is a singleton code schematic, refer to the following:

// 定义一个单例类
class Singleton {
public:
  // 获取单例对象的方法
  static Singleton* getInstance() {
    // 定义一个静态局部变量,它会在第一次调用时初始化,并且是线程安全的
    static Singleton instance;
    // 返回该变量的地址,即单例对象的指针
    return &instance;
  }
  // 定义其他的成员函数和变量
  // ...
private:
  // 将构造函数、拷贝构造函数、赋值运算符和析构函数设为私有,防止外部创建或销毁对象
  Singleton() {
    // ... // 初始化代码
  }
  ~Singleton() {
    // ... // 清理代码
  }
  Singleton(const Singleton&) = delete;
  Singleton& operator=(const Singleton&) = delete;
};

The main logic and functions of the above code can be learned and understood by referring to the following content:

  • The purpose of this code is to define a singleton class, that is, a class that can have only one instance, and provide a global point of access.
  • First, a class named Singleton is defined, indicating that this is a singleton class.
  • Then, a static member function getInstance is defined in the class, which is used to obtain the pointer of the singleton object. This function is the only public interface of the class, and the outside can only access the singleton object through it.
  • In the getInstance function, a static local variable instance is defined, which is an object of the Singleton class. This variable will be initialized when the getInstance function is called for the first time, and it is thread-safe in the C++11 standard, that is, it will not be initialized by multiple threads at the same time. This ensures that only one Singleton object is created.
  • Then, return the address of the instance variable, which is the pointer to the singleton object. In this way, a global access point is provided, and the singleton object can be obtained externally through Singleton::getInstance().
  • Next, other member functions and variables are defined in the class to realize the specific functions of the class. These member functions and variables are private and cannot be accessed directly from the outside.
  • Finally, make the constructor, copy constructor, assignment operator, and destructor private in the class, and use the delete keyword to prohibit copying and assignment. This prevents external creation or destruction of singleton objects and ensures the correctness of singleton patterns.

another example:

To reduce the software written by Qt to the taskbar, you can implement the following steps:
Create a QSystemTray object in the code, which is used to create the system tray icon. Set properties such as icon, title and menu of QSystemTray object. Adds a QSystemTray object to a Qt application's window system. In the code, the function of minimizing the application window to the system tray can be realized by calling the setWindowState() function of the QWindow class.
Here is a simple sample code that demonstrates how to shrink a Qt application window to the taskbar:

#include <QApplication>  
#include <QWidget>  
#include <QSystemTray>  
#include <QMenu>  
#include <QAction>
int main(int argc, char *argv[])  
{
   QApplication app(argc, argv);
   QWidget window;  
   QSystemTray tray;
   // 设置系统托盘图标  
   QIcon icon(":/icons/tray_icon.png");  
   tray.setIcon(icon);
   // 设置系统托盘标题  
   tray.setTitle("My Application");
   // 设置系统托盘菜单  
   QMenu *menu = new QMenu("&File", &tray);  
   QAction *openAction = new QAction("&Open", &tray);  
   QAction *closeAction = new QAction("&Close", &tray);  
   connect(openAction, &QAction::triggered, [=]() {  
       window.show();  
   });  
   connect(closeAction, &QAction::triggered, [=]() {  
       window.close();  
   });  
   menu->addAction(openAction);  
   menu->addAction(closeAction);  
   tray.setMenu(menu);
   // 将系统托盘添加到窗口系统中  
   window.installSystemTray(&tray);
   // 实现将应用程序窗口最小化到系统托盘的功能  
   connect(&tray, &QSystemTray::activated, [=]() {  
       if (tray.isVisible()) {  
           window.setWindowState(QWindow::WindowMinimized);  
       } else {  
           window.setWindowState(QWindow::WindowActive);  
       }  
   });
   window.show();  
   return app.exec();  
}

In the sample code above, we first created a QWidget object to display the application's main window. Then, we created a QSystemTray object and set its icon, title and menu properties. Next, we add the QSystemTray object to the Qt application's window system. Finally, we implement the function of minimizing the application window to the system tray by calling the setWindowState() function of the QWindow class.
When the user clicks the system tray icon, the activated signal of the QSystemTray object will be triggered, thereby realizing the function of minimizing the application window to the system tray. When the application window is minimized to the system tray, the user can restore the application window by right-clicking the system tray icon and selecting the "Show window" option.

In addition to using QSystemTray to minimize the application window to the taskbar, you can also use third-party libraries such as QStyleHint to achieve similar functions.
Here is a sample code using the QStyleHint library:

#include <QApplication>  
#include <QWidget>  
#include <QStyleHint>  
#include <QMenu>  
#include <QAction>
int main(int argc, char *argv[])  
{
   QApplication app(argc, argv);
   QWidget window;  
   QStyleHint *styleHint = new QStyleHint();
   // 设置窗口最小化到任务栏的提示信息    
   styleHint->setHint(QStyleHint::TaskBarWindowMinimizeHint, true);
   // 设置系统托盘图标    
   QIcon icon(":/icons/tray_icon.png");  
   styleHint->setHint(QStyleHint::IconSize, QSize(icon.size().width(), icon.size().height()));  
   styleHint->setHint(QStyleHint::IconSpacing, 4);
   // 设置系统托盘标题    
   styleHint->setHint(QStyleHint::TaskBarTitle, "My Application");
   // 设置系统托盘菜单    
   QMenu *menu = new QMenu("&File", window);  
   QAction *openAction = new QAction("&Open", window);  
   QAction *closeAction = new QAction("&Close", window);  
   connect(openAction, &QAction::triggered, [=]() {  
       window.show();  
   });  
   connect(closeAction, &QAction::triggered, [=]() {  
       window.close();  
   });  
   menu->addAction(openAction);  
   menu->addAction(closeAction);
   // 将窗口添加到任务栏    
   window.setWindowState(QWindow::WindowActive);  
   window.installStyleHint(styleHint);
   window.show();  
   return app.exec();  
}

In this example, we first create a QWidget object to display the application's main window. Then, we created a QStyleHint object and set properties such as prompt information, system tray icon, title and menu when the window is minimized to the taskbar. Next, we add the window to the taskbar and install QStyleHint.
In this way, when the user clicks on the window title bar, the window will be minimized to the taskbar; when the user right-clicks the system tray icon, he can also select the "Show Window" option to restore the application window.
Note: When using QStyleHint, you need to call the QWidget::installStyleHint() function to install the style hint on the window. Also, QStyleHint is only available for Qt 5.15 and later.

Guess you like

Origin blog.csdn.net/Helloorld_1/article/details/132183077