,這樣我就重複一個具體的行動(點擊一個按鈕或網絡請求的)。如何使用QTimer重複我有了解如何使用<code>QTimer</code>問題的具體行動
繼answer從這個漂亮的question,我無法弄清楚如何定時器的QTimer::Timeout
信號連接到MainWIndow::request
信號以同樣的方式,因爲我有當前連接的按鈕。問題是我無法重複它;它編譯和運行沒有錯誤,但沒有重複。
(喜歡誰張貼問題的人,我也可以有定時器重複,如果我把我所有的代碼在main.cpp
,但我想看看究竟是如何能在這種情況下完成的。)
下面是從例如採取了簡化代碼,以我的嘗試:
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QKeyEvent>
#include <QApplication>
#include <QtWidgets>
#include <QTimer>
MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow)
{
ui->setupUi(this);
// GUI setup here //
networkManager = new QNetworkAccessManager;
connect(networkManager, &QNetworkAccessManager::finished, this, &MainWindow::on_NetworkManagerFinished);
connect(ui->getButton, &QPushButton::clicked, this, &MainWindow::on_getButton_clicked);
// Connect the timer to repeat the GET request
QTimer timer;
// [1st attempt]
connect(&timer, SIGNAL(&QTimer::timeout), this, SLOT(&MainWindow::on_TimerTimeout));
// [2nd attempt]
connect(&timer, SIGNAL(timeout()), this, SLOT(timer_buttonClicked()));
timer.start(1500); // 1.5 secs
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::on_NetworkManagerFinished(QNetworkReply *reply)
{
// Parse and display JSON here //
}
// Make GET request when button is clicked
void MainWindow::on_getButton_clicked() //on_TimerTimeout()
{
// Make GET request
QUrlQuery query;
QUrl url("http://blah/blahblah");
query.addQueryItem("blah", "blah");
url.setQuery(query);
QNetworkRequest networkRequest(url);
networkManager->get(networkRequest);
ui->getButton->setEnabled(false);
// Restart timer
timer->start(1500); // 1.5 secs
// Do stuff in the GUI here //
}
更新
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
private slots:
void on_NetworkManagerFinished(QNetworkReply* reply);
void on_getButton_clicked();
private:
Ui::MainWindow *ui;
QNetworkAccessManager *networkManager;
};
#endif // MAINWINDOW_H
因爲它可以在評論部分中看到,我還嘗試在mainwindow.h
中用onTimeout替換該按鈕的專用插槽,並在mainwindow.cpp
之前用connect創建了一個QTimer對象並啓動它,之後我使用該對象定義connect(&timer,&QTimer::timeout,this,&MainWindow::onTimeout);
。另外,我用onTimeout相關代碼替換了最後的按鈕槽定義。
如果你能解釋我缺少的東西,或者甚至提供精確範例的代碼,如here這對我來說很好理解。
您在構造函數中創建了一個本地計時器,這意味着計時器在構造函數返回後被銷燬。動態分配它'QTimer * timer = new QTimer'或更好 - 使定時器成爲類成員。 – dtech
我非常懷疑你希望定時器點擊按鈕或任何類型的東西。您希望計時器調用連接到按鈕單擊的任何操作。這是完全不同的。 –