「Qtの基礎 - タイマ」の版間の差分

提供:MochiuWiki : SUSE, EC, PCB
ナビゲーションに移動 検索に移動
(ページの作成:「== 概要 == Qtにおいて、<code>QTimer</code>クラスを使用して、様々な処理を実行する手順を記載する。<br> <br><br> == QTimerを即タイム…」)
 
16行目: 16行目:
そして、プッシュボタンを押下し続けている間、1秒毎に1増加している。<br>
そして、プッシュボタンを押下し続けている間、1秒毎に1増加している。<br>
  <syntaxhighlight lang="c++">
  <syntaxhighlight lang="c++">
// MainWindow.h
  #pragma once
  #pragma once
   
   
42行目: 44行目:
<br>
<br>
  <syntaxhighlight lang="c++">
  <syntaxhighlight lang="c++">
// MainWindow.cpp
#include <MainWindow.h>
  MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow), m_Timer(nullptr), m_Val(0)
  MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow), m_Timer(nullptr), m_Val(0)
  {
  {

2021年2月16日 (火) 16:37時点における版

概要

Qtにおいて、QTimerクラスを使用して、様々な処理を実行する手順を記載する。


QTimerを即タイムアウトする

QTimerクラスのtimeoutメソッドに、{}を渡す。

 timer->timeout({});


一般的に、timeoutシグナルを接続したスロット関数では、以降変更しない場合、
QTimerクラスのstartメソッドを実行する前に、直接スロット関数を1度呼ぶ。
しかし、接続するスロット関数を動的に変更する場合、timeoutメソッドを呼ぶだけの方が便利である。

以下の例では、プッシュボタンとラベルを配置して、プッシュボタンを押下した直後にタイマを開始している。
そして、プッシュボタンを押下し続けている間、1秒毎に1増加している。

 // MainWindow.h
 
 #pragma once
 
 #include <QMainWindow>
 #include <memory>
 
 class MainWindow : public QMainWindow
 {
    Q_OBJECT
 
 public:
    explicit MainWindow(QWidget *parent = nullptr);
    ~MainWindow();
 
 private slots:
    void on_pushButton_pressed();
    void on_pushButton_released();
 
 private:
    Ui::MainWindow *ui;
    std::unique_ptr<QTimer> m_Timer;
    int m_Val;
    void timerFunc();
 };


 // MainWindow.cpp
 
 #include <MainWindow.h>
 
 MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow), m_Timer(nullptr), m_Val(0)
 {
    ui->setupUi(this);
 
    ui->label->setText(QString::number(val));
 
    m_Timer = std::make_unique<QTimer>(this);
 
    connect(m_Timer, &QTimer::timeout, this, &MainWindow::timerFunc);
 }
 
 MainWindow::~MainWindow()
 {
    delete ui;
 }
 
 void MainWindow::on_pushButton_pressed()
 {
    m_Timer->timeout({});
    m_Timer->start(1000);
 }
 
 void MainWindow::on_pushButton_released()
 {
    m_Timer->stop();
 }
 
 void MainWindow::timerFunc()
 {
    m_Val++;
    ui->label->setText(QString::number(m_Val));
 }