Qt Tab rename when double clicked

1.3k views Asked by At

i am using visual Studio with Qt. i do not have access to Qt designer. its all done through coding (C++);

i have an opensource software called easypaint.

i got stuck at trying to rename tabs. I want to be able to rename tabs when user double clicks on the tab itself.

i created a new function to filter the doubleClick event :

 bool MainWindow::eventFilter(QObject *obj, QEvent *event)
 `enter code here`{
     if (event->type() == QEvent::MouseButtonDblClick) {
         return true;
     } else {
         // standard event processing
         return QObject::eventFilter(obj, event);
     }
 }

then i added this line to a function that initializes the TabWidget:

installEventFilter(mTabWidget);

can anyone please guide me through this. Thank you

2

There are 2 answers

5
St0fF On BEST ANSWER

Most likely Qt doesn't allow an inline editor to open on the tab's name. So you'd most likely have to create and run a very small QDialog to query for the new name:

 bool MainWindow::eventFilter(QObject *obj, QEvent *event)
 {
    if (obj == mTabWidget &&
        event->type() == QEvent::MouseButtonDblClick) {

        // query and set tab(s) names
        QTabWidget *tab = qobject_cast<QTabWidget *>(obj);
        if(tab)
        {
            QDialog dlg;
            QVBoxLayout la(&dlg);
            QLineEdit ed;
            la.addWidget(&ed);
            QDialogButtonBox bb(QDialogButtonBox::Ok | QDialogButtonBox::Cancel);
            la.addWidget(&bb);
            dlg.setLayout(&la);
            if(dlg.exec() == QDialog::Accepted)
            {
                tab->setTabText(0, ed.text());
                return true;
            }
        }
    }

    // Standard event processing
    return QObject::eventFilter(obj, event);
}

It might be that Qt's dynamic memory management doesn't like the local class instances, so you'd have to convert all those class instances created to pointers created with new, but then please don't forget to tell the QDialog to delete on close or call dlg->deleteLater() after you queried the new name.

Another way to solve this via a fake inline editor would need a bit more work:

  • create a QLineEdit
  • move it right above the tab's, bring it up front and set keyboard focus to it
  • wire signals and slots
    • pressing enter should use the contents of the QLineEdit
    • leaving focus from the line edit should be treated as "abort" and delete the line editor
  • implement the slots to do what's needed.
0
vahancho On

You can write the event filter in the fallowing way:

bool MainWindow::eventFilter(QObject *obj, QEvent *event)
{
     if (obj == mTabWidget &&
         event->type() == QEvent::MouseButtonDblClick) {

         QTabWidget *tab = qobject_cast<QTabWidget *>(obj);
         // Set tab(s) names         
         tab->setTabText(0, "New Name");
     }

     // Standard event processing
     return QObject::eventFilter(obj, event);
 }