How to change MDI subWindow icon?

2019-06-24 01:27发布

问题:

Look at the following Image:

I have created the Sub Window dynamically.

I'm tried to use setWindowIcon function like the following:

mdiWindows->setWindowIcon(QIcon("icon.ico"));

But does not works fine.

Also see the following code (MDI window creation):

QWidget *widget = new QWidget(this);
QTextEdit *TextEdit = new QTextEdit(widget);
TextEdit->setObjectName("myTextEdit");
QMdiSubWindow *mdiWindows = ui->mdiArea->addSubWindow(widget);
mdiWindows->setGeometry(5, 5, 300, 250);
mdiWindows->setWindowTitle("untitled" + QString::number(ui->mdiArea->subWindowList().count()));
mdiWindows->setWindowState(Qt::WindowMaximized);
mdiWindows->layout()->addWidget(TextEdit);
mdiWindows->layout()->setContentsMargins(0,0,0,
mdiWindows->layout()->setSpacing(
mdiWindows->show();

How to change MDI subWindow icon ?

回答1:

What's wrong?

I'm tried to use setWindowIcon function like the following: mdiWindows->setWindowIcon(QIcon("icon.ico"));

But you have done wrong, because:

  1. You set icon on mdiWindow itself rather than it's subWindow.
  2. Besides, .ico is for Application icon in Windows, you should just use .jpg or .png format. The details of default supporting format list can be found here.

(If you insist on .ico file, there is a workaround. Check: ".ico icons not showing up on Windows")


Solution:

Therefore, change this line mdiWindows->setWindowIcon(QIcon("icon.ico"));

into: widget->setWindowIcon(QIcon(":/myIcon/icon.png"));

(Notice that you can do the same on other QWidget derivatives: QMainWindow, QDialog...etc to set their window icon)

In other words, insert the above line into your code:

//QWidget *widget = new QWidget(this);
//QTextEdit *TextEdit = new QTextEdit(widget);
//TextEdit->setObjectName("myTextEdit");
widget->setWindowIcon(QIcon(":/myIcon/icon.png")); 
//QMdiSubWindow *mdiWindows = ui->mdiArea->addSubWindow(widget);
//mdiWindows->setGeometry(5, 5, 300, 250);
//mdiWindows->setWindowTitle("untitled" + QString::number(ui->mdiArea->subWindowList().count()));
//mdiWindows->setWindowState(Qt::WindowMaximized);
//mdiWindows->layout()->addWidget(TextEdit);
//mdiWindows->layout()->setContentsMargins(0,0,0,
//mdiWindows->layout()->setSpacing(
//mdiWindows->show();


P.S.

Just in case, if you want to set them later, you can call QMdiArea::subWindowList() to get the list of mdiWindows then set icons on them separately. For example:

mdiWindows->subWindowList().at(1)->setWindowIcon(QIcon(":/myIcon/icon.png"));

This works the same.



标签: c++ qt qt5