c++qtqwidgetqtguiqmainwindow

How to change window title and central widget in Qt?


Hi, I have a problem with changing window title and central widget in Qt. There is MainWindow:

class MainWindow : public QMainWindow
  {
// (...)
  QStackedWidget* widgets;
  Quiz* widget1, *widget2;
  }

and there is a class Quiz:

class Quiz : public QWidget
  {
  public slots:
    void myClicked();
  }

I wanted to change MainWindow title after clicking on button, which is a element of Quiz (and it is connected with slot myClicked).

void Quiz::myClicked()
 {
 static_cast<MainWindow>(parent).myFunction();
 }

void MainWindow::myFunction()
{
widget2 = new Quiz(this,2);
widgets->addWidget(widget2);
std::cout<<"current wdgt: " << widgets->currentIndex() << std::endl; // shows: 0
widgets->setCurrentWidget(widget2);
std::cout<<"current wdgt " << widgets->currentIndex() << std::endl; // shows: 1

setWindowTitle("newTitle");
std::cout<<"Title is " << windowTitle().toStdString() << std::endl;

}

So widgets->currentIndex shows index of new widget but nothing is changed in my window. The same problem is with window title - method windowTitle() returns new title, but title on a titlebar is old. Why? If I change title in Quiz::myClicked by:

parent->setWindowTitle("newTitle");

it works! Why it works how strange? Please help.


Solution

  • it works! Why it works how strange? Please help.

    It is not strange. That is how the Qt API is designed. See the documentation for the explanation:

    windowTitle : QString

    This property holds the window title (caption).

    This property only makes sense for top-level widgets, such as windows and dialogs.

    Let us analyze the last sentence: your quiz is neither a QMainWindow, nor a QDialog, hence it cannot work. Windows titles only make sense for those based on the documentation. When you call it on the parent, it will work respectively since that is a QMainWindow.