我正在编写基于Qt的应用程序,每次用户更改活动文档时都需要更新MainWindow标题。标题构建如下:“AppName - DocumentName”。
如果我理解正确,当我通过QWidget::setWindowTitle
方法设置新标题时,旧的QString
标题被取消分配并设置新标题。但是在我的应用程序执行期间它会导致很多malloc / free调用。
有没有可能为标题预分配QString
和一些备用的长DocumentName字符串,并在第一个setWindowTitle
之后获得一个引用(不是副本)到这个新的标题字符串,然后只是替换现有标题中所需的部分,然后以某种方式迫使这个更新的标题刷新?
你可以尽可能多地改变标题,你不需要释放内存,只需给方法一个有效的字符串:
setWindowTitle(const QString &);
以下示例每秒更改标题设置的日期和时间:
MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow)
{
ui->setupUi(this);
myTimer = new QTimer(this);
myTimer->setInterval(1000);
connect(myTimer, &QTimer::timeout, this, &MainWindow::changeWinTitle);
myTimer->start();
}
MainWindow::~MainWindow()
{
delete ui;
myTimer->stop();
delete myTimer;
}
void MainWindow::changeWinTitle()
{
auto dateString{"Now: " + QDateTime::currentDateTime().toString()};
qDebug() << dateString;
this->setWindowTitle(dateString);
}