Я хочу послать сигнал подключения после нажатия и удержания кнопки в течение определенного времени. По истечении этого времени (например, 10 секунд) действие или событие будут инициированы, даже если кнопка не будет отпущена. Это могут быть комбинации нажатия или удержания на какое-то время или что-то иное, чем просто нажатие и отпускание кнопки.
Вот код, который я тестировал на PyQt4
import sys
from PyQt4.QtCore import *
from PyQt4.QtGui import *
class MainWindow(QWidget):
def __init__(self):
super().__init__()
#Creation of a sample Window
self.textLabel = QLabel()
self.textLabel.setText('This is a Sample Window')
box = QHBoxLayout(self)
box.addWidget(self.textLabel)
#Create a Timer
self.timer = QTimer()
self.timer.timeout.connect(lambda: self.mouse_event_check())
self.held_time = 0
#Create Sample Button
self.button = QPushButton('SAMPLE BUTTON')
box.addWidget(self.button)
#Connect Signals Pressed and Released
self.button.pressed.connect(self.button_pressed)
self.button.released.connect(self.button_released)
self.timer_button = QTimer()
self.timer_button.timeout.connect(lambda: self.button_event_check())
self.button_held_time = 0
# =========================================================================
# Implementation for Buttons
# =========================================================================
def button_pressed(self):
self.timer_button.start(50)
def button_released(self):
self.timer_button.stop()
print('Button Held for {:.4f} seconds'.format(self.button_held_time))
self.button.setText('{:.4f} seconds'.format(self.button_held_time))
self.button_held_time = 0
def button_event_check(self):
self.button_held_time += 0.05
# =========================================================================
# Implmentation for Mouse Held on Window
# =========================================================================
def mousePressEvent(self, mouse_event):
self.timer.start(50)
def mouse_event_check(self):
self.held_time += 0.05
def mouseReleaseEvent(self, mouse_event):
self.timer.stop()
print('Mouse Held for {:.4f} seconds'.format(self.held_time))
self.textLabel.setText('Mouse Held for {:.4f} seconds'.format(self.held_time))
self.held_time = 0
if __name__ == '__main__':
app = QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec_())
held_time
. Установите 0mouse_event_check
)MousePressEvent()
MouseReleaseEvent()
held_time
до 0mouse_event_check()
button_held_time
. Установите 0button_event_check
)pressed
и released
к некоторым вызываемымpressed
метод released
метод button_held_time
на 0button_event_check()
mouse_event
. Это работает с кнопкой? или у кнопок было что-то похожее? (как; button_event)
QPushButton
используя встроенные сигналы pressed
и released
. Надеюсь, это поможет.
Я думаю, что вы можете положиться на использование QTimer, то есть когда пользователь нажимает кнопку, вы можете запустить какой-нибудь экземпляр QTimer с указанным интервалом, а когда QTimer истечет, затем активировать сигнал. В случае, если пользователь прерывает действие, QTimer можно просто сбросить, и тогда сигнал не сработает. Пример кода можно увидеть ниже. Тем не менее, это в C++, но, возможно, это не будет проблемой для вас.
Итак, ниже приведено определение MainWindow:
#pragma once
#include <memory>
#include <QMainWindow>
namespace Ui
{
class MainWindow;
}
class MainWindow
: public QMainWindow
{
Q_OBJECT
public:
MainWindow(QWidget *parent = nullptr);
virtual ~MainWindow();
signals:
void SomeTimerSignal(); // Signal we are eager to fire on the specific event.
public slots:
void ButtonPressed(); // Button is clicked down.
void ButtonReleased(); // Button is released.
void OnTimeout(); // Timeout handling slot.
private:
std::unique_ptr<Ui::MainWindow> m_ui; // UI mockup that is provided by Qt for us under the hood.
QTimer* m_buttonTimer; // The timer we are going to control.
};
А теперь сам код, реализующий это определение:
#include <QPushButton>
#include <QTimer>
#include <QVBoxLayout>
#include "MainWindow.h"
#include "ui_MainWindow.h"
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, m_ui(new Ui::MainWindow())
{
m_ui->setupUi(this);
// We could have chosen to instantiate timers on each signal, but it is much more efficient
// to create an instance of it once, and then use it appropriately.
m_buttonTimer = new QTimer(this);
// OnTimeout will get triggered after 10 seconds.
m_buttonTimer->setInterval(10000);
connect(m_buttonTimer, &QTimer::timeout, this, &MainWindow::OnTimeout);
auto layout = new QVBoxLayout();
auto button = new QPushButton();
button->setText("Click and hold me!");
button->setFixedSize(150, 50);
layout->addWidget(button);
m_ui->centralWidget->setLayout(layout);
// Listen to button being pressed down: https://doc.qt.io/qt-5/qabstractbutton.html#pressed
connect(button, &QPushButton::pressed, this, &MainWindow::ButtonPressed);
// Listen to button being released: https://doc.qt.io/qt-5/qabstractbutton.html#released
connect(button, &QPushButton::released, this, &MainWindow::ButtonReleased);
}
MainWindow::~MainWindow()
{
// Button timer will be taken care by Qt through its' memory model.
}
void MainWindow::ButtonPressed()
{
// Start the timer when button is pressed.
m_buttonTimer->start();
}
void MainWindow::ButtonReleased()
{
// Stop the timer, but don't delete it, since it can be reused.
m_buttonTimer->stop();
}
void MainWindow::OnTimeout()
{
// On timeout, we stop the timer, so it would not be triggered all over again when not needed.
m_buttonTimer->stop();
// And we fire some wanted signal.
emit SomeTimerSignal();
}
Чтобы использовать этот код, вы, вероятно, захотите создать экземпляр приложения следующим образом:
#include "MainWindow.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.show();
return a.exec();
}
Другими словами, это довольно простое приложение Qt в C++, которое заполняется для вас при создании вашего первого проекта Qt, если вы используете Qt Creator. Надеюсь, этот код проясняет идею, как вы могли бы достичь того, что вы хотите. Если у вас есть еще вопросы, пожалуйста, задавайте их. Надеюсь, я смогу вам помочь.
Попытайся:
import sys
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
class MainWindow(QWidget):
def __init__(self):
super().__init__()
self.textLabel = QLabel()
button = QPushButton("Click me")
button.clicked.connect(self.clickedButton)
grid = QGridLayout(self)
grid.addWidget(self.textLabel)
grid.addWidget(button)
def clickedButton(self):
QTimer.singleShot(3000, self.passed3seconds) # <---
def passed3seconds(self):
self.textLabel.setText("3 seconds passed \n do something")
if __name__ == '__main__':
app = QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec_())
if self.held_time>10.0000:
print('alo')
в mouse_event_check (), это будет работать так, как я хочу.