User Tools

Site Tools

blog:2021-02-20_qt_get_part_of_qstring



2021-02-20 Qt: Get part of QString

  • I want to get QString from another QString with the necessary indexes.

Method

  • Using left(), mid() and right() can do that
        QString myString("abcdefghijklmnopqrstuvwxyz");
        MainWindow::ui->textEdit_Log->append(myString);
        QString subString = myString.mid(5,2); // subString contains "fg"
        MainWindow::ui->textEdit_Log->append(subString);
        subString.append("!@#"); // subString contains "fg!@#"
        MainWindow::ui->textEdit_Log->append(subString);"

    Result:
  • Example:
        // 宣告 1 秒的Timer
        var_timer_1s = startTimer(1000);
        currentTimeLabel = new QLabel; // 顯示時間的Label元件宣告
        ui->statusbar->addWidget(currentTimeLabel); // 在狀態欄中加入顯示時間的Label元件
        ...
        ...
        ...
        // 每秒固定的 Tasks
        // Update Date & Time
        var_current_time = QDateTime::currentDateTimeUtc(); // 獲得目前UTC時間
        var_timestr = var_current_time.toString( "yyyy-MM-ddThh:mm:ssZ"); // 設定顯示時間的格式
        currentTimeLabel->setText(var_timestr); // 更新狀態欄中現在時間
        ...
        ...
        // Get time from the date-time-string
        MainWindow::ui->textEdit_Log->append(var_timestr.mid(11,8)+": " + str);
        ...
        

Reference

  • QString left(int n) const
  • QString leftJustified(int width, QChar fill = QLatin1Char(' '), bool truncate = false) const
  • QStringRef leftRef(int n) const
  • QString mid(int position, int n = -1) const
  • QStringRef midRef(int position, int n = -1) const
  • QString right(int n) const
  • QString rightJustified(int width, QChar fill = QLatin1Char(' '), bool truncate = false) const
  • QStringRef rightRef(int n) const

TAGS

  • 264 person(s) visited this page until now.

Permalink blog/2021-02-20_qt_get_part_of_qstring.txt · Last modified: 2021/02/20 17:41 by jethro

oeffentlich