Search code examples
c++qtqt5duplication

Check if a dialog/widget/window still open to prevent the duplication


How to prevent open a window many times.

See the following image:

What I want is if the window still open does not open the same window once again except after closure the open window.

Finally, the code:

void Widget::on_search_btn_clicked(){
    searchItem *searchBox = new searchItem;
    searchBox->setModal(false);  // <--- I want this as it is
    searchBox->show();
    searchBox->activateWindow();
}

Solution

  • A solution is to :

    1. Add searchItem *searchBox as member of your class.

      private:
          searchItem* m_searchBox;
      
    2. Initialize with new searchItem() in the constructor.

      Widget::Widget() {
          ...
          m_searchBox = new searchItem();
      }
      
    3. Call void Widget::on_search_btn_clicked() and use functions on m_searchBox (consequently this is the only window that will be opened, even if it's already opened)

      void Widget::on_search_btn_clicked(){
          m_searchBox->setModal(false);
          m_searchBox->show();
          m_searchBox->activateWindow();
      }
      
    4. Delete in destructor

      Widget::~Widget() {
          ...
          delete m_searchBox;
      }