How to convert Q_ENUM to QString for QT > 5.11 most efficient way?

不问归期 提交于 2021-02-05 08:51:35

问题


I read several advices how to get an actual QString from a Q_ENUM value.

Below are 3 possible ways, I came up with, that are compilable constructs in QT5.11.1

What of them should one prefer and why?

void MainWindow::setErrorText(QCanBusDevice::CanBusError error)
{
    QString errorString;
    QDebug(&errorString) << error;
    ui->statusBar->showMessage("Error occured: " + errorString);

    // QT4 ?
    const QMetaObject& mo = QCanBusDevice::staticMetaObject;
    QMetaEnum me = mo.enumerator(mo.indexOfEnumerator("CanBusError"));
    QString errorStr(me.valueToKey(QCanBusDevice::UnconnectedState));
    ui->statusBar->showMessage("Error occured: " + errorStr);

   // From QT5?
   QString errorS(QMetaEnum::fromType<QCanBusDevice::CanBusError>().valueToKey(error));
   ui->statusBar->showMessage("Error occured: " + errorS);
}

回答1:


QDebug should be used for logging and debugging. QDebug constructs a QTextStream and is quite expensive for what you're trying to do.

Using QMetaEnum is proper. You shouldn't be doing string concatenation the way you do, use tr for user visible strings, or QStringLiteral instead of tr elsewhere:

const auto errStr = QMetaEnum::fromType<QCanBusDevice::CanBusError>().valueToKey(error);
ui->statusBar->showMessage(tr("Error occured: %1").arg(errStr));



回答2:


Another, more elegant way, is by using QVariant's toString() method:

QString errStr = QVariant::fromValue(error).toString();
ui->statusBar->showMessage("Error occured: " + errStr);


来源:https://stackoverflow.com/questions/53208511/how-to-convert-q-enum-to-qstring-for-qt-5-11-most-efficient-way

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!