我正在编写基于 Qt 的应用程序,每次用户更改事件文档时都需要更新主窗口标题。标题构建如下:“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);
}
关于c++ - 用新的 QString 优化替换 windowTitle,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54690517/