1

QString我阅读了一些关于如何从值中获取实际值的建议Q_ENUM

以下是我想出的 3 种可能的方法,它们是 QT5.11.1 中的可编译构造

他们应该更喜欢哪一个,为什么?

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);
}
4

2 回答 2

3

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));
于 2018-11-08T13:52:15.523 回答
2

另一种更优雅的方法是使用 QVariant 的 toString() 方法:

QString errStr = QVariant::fromValue(error).toString();
ui->statusBar->showMessage("Error occured: " + errStr);
于 2019-01-23T15:46:05.677 回答