Python count How many Clicks are in a second - python

Would someone mind helping me with this? I'm trying to make a clicks per second test like this one on this website.
I've tried many different things, but I couldn't figure it out
Here are my imports
from PyQt4.QtCore import QSize
from PyQt4.QtGui import QApplication, QMainWindow, QPushButton, QWidget, QIcon, QLabel, QPainter, QPixmap
here is my code
class UICPS(QWidget): #||| CPS TAB |||
def __init__(self, parent=None):
super(UICPS, self).__init__(parent)
clicks = 0
self.Back = QPushButton("<- Back", self)
self.Back.resize(50,25)
self.Back.move(0, 425)
self.Clicked = QLabel(str(clicks), self)
self.Clicked.move(200, 200)
self.CPSBTN = QPushButton("Click Me!", self)
self.CPSBTN.resize(400, 175)
self.CPSBTN.move(0, 250)
if self.Clicked:
clicks +1

My Solution:
import sys
from PyQt4.QtCore import QTimer
from PyQt4.QtGui import QApplication, QLabel, QPushButton, QWidget
class UICPS(QWidget):
def __init__(self, parent=None):
super(UICPS, self).__init__(parent)
self.clicks = 0
self.Back = QPushButton("<- Back", self)
self.Back.resize(50, 25)
self.Back.move(0, 425)
self.ClickedLB = QLabel(str(self.clicks), self)
self.ClickedLB.resize(400, 20)
self.ClickedLB.move(200, 100)
self.ClickedLB2 = QLabel(str(self.clicks), self)
self.ClickedLB2.resize(400, 20)
self.ClickedLB2.move(200, 150)
self.ClickedLB3 = QLabel(str(self.clicks), self)
self.ClickedLB3.resize(400, 20)
self.ClickedLB3.move(200, 200)
self.CPSBTN = QPushButton("Click Me!", self)
self.CPSBTN.clicked.connect(self.Clicked)
self.CPSBTN.resize(400, 175)
self.CPSBTN.move(0, 250)
self.resize(400, 450)
self.starting = False
self.timer = QTimer(self)
self.timer.timeout.connect(self.updateClock)
self.counter = 0
self.isFist = True
def updateClock(self):
self.counter += 0.01
self.ClickedLB2.setText("%.2f s" % self.counter)
if self.counter >= 9.99:
self.starting = False
cps = self.clicks/10
self.ClickedLB3.setText("%.2f CPS" % cps)
self.timer.stop()
def Clicked(self):
if self.starting:
self.clicks += 1
self.ClickedLB.setText(str(self.clicks))
else:
if self.isFist:
self.timer.start(10)
self.starting = True
self.isFist = False
if __name__ == '__main__':
app = QApplication(sys.argv)
w = UICPS()
w.show()
sys.exit(app.exec_())
After clicked:

You have to assign function to button
from PyQt4 import QtGui
import sys
class MyWindow(QtGui.QWidget):
def __init__(self, parent=None):
super(MyWindow, self).__init__()
self.clicks = 0
self.vbox = QtGui.QVBoxLayout()
self.setLayout(self.vbox)
self.label = QtGui.QLabel(str(self.clicks), self)
self.vbox.addWidget(self.label)
self.button = QtGui.QPushButton("Click Me!", self)
self.vbox.addWidget(self.button)
# assign function to button
self.button.clicked.connect(self.on_click)
self.show()
def on_click(self):
self.clicks += 1
self.label.setText(str(self.clicks))
app = QtGui.QApplication(sys.argv)
win = MyWindow()
app.exec_()

Related

KeyPressEvent() doesn't work with label when I add PushButtons

`
from PyQt5.QtCore import Qt
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow
from PyQt5.QtWidgets import QLabel, QPushButton
class Example(QMainWindow):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
self.setGeometry(300, 300, 1000, 1000)
self.setWindowTitle('Example')
self.label_backround = QLabel(self)
self.label_backround.move(100, 100)
self.label_backround.resize(800, 800)
self.label = QLabel(self)
self.label.setText("xxxxx")
self.label.move(340, 340)
self.Button1 = QPushButton('1', self)
self.Button1.move(580, 250)
self.Button2 = QPushButton('2', self)
self.Button2.move(590, 560)
self.Button3 = QPushButton('3', self)
self.Button3.move(210, 660)
def keyPressEvent(self, event):
x = self.label.x()
y = self.label.y()
if event.key() == Qt.Key_Left:
self.label.move(x - 15, y)
elif event.key() == Qt.Key_Up:
self.label.move(x, y - 15)
elif event.key() == Qt.Key_Right:
self.label.move(x + 15, y)
elif event.key() == Qt.Key_Down:
self.label.move(x, y + 15)
app = QApplication(sys.argv)
ex = Example()
ex.show()
sys.exit(app.exec_())
`I have a window on which is a label that should move when I press the up, down, right and left buttons on keyboard. It works, but when I add some PushButtons the label doesn't move.
Сan anyone know what this is about?
The widget that receives the keypress event only the widget that has the focus, and by default many widgets like the QPushButtons take the focus unlike a QWidget. In this case you should not use keyPressEvent but a QShorcut that allows you to capture keyboard events independently of the widgets (obviously you can set limitations through context). Considering the above, the solution is:
import sys
from PyQt5.QtCore import QPoint, Qt
from PyQt5.QtGui import QKeySequence
from PyQt5.QtWidgets import QApplication, QLabel, QMainWindow, QPushButton, QShortcut
class Example(QMainWindow):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
self.setGeometry(300, 300, 1000, 1000)
self.setWindowTitle("Example")
self.label_backround = QLabel(self)
self.label_backround.move(100, 100)
self.label_backround.resize(800, 800)
self.label = QLabel(self)
self.label.setText("xxxxx")
self.label.move(340, 340)
self.Button1 = QPushButton("1", self)
self.Button1.move(580, 250)
self.Button2 = QPushButton("2", self)
self.Button2.move(590, 560)
self.Button3 = QPushButton("3", self)
self.Button3.move(210, 660)
QShortcut(QKeySequence(Qt.Key_Left), self, activated=self.move_left)
QShortcut(QKeySequence(Qt.Key_Up), self, activated=self.move_up)
QShortcut(QKeySequence(Qt.Key_Right), self, activated=self.move_right)
QShortcut(QKeySequence(Qt.Key_Down), self, activated=self.move_down)
def move_left(self):
self.label.move(self.label.pos() + QPoint(-15, 0))
def move_up(self):
self.label.move(self.label.pos() + QPoint(0, -15))
def move_right(self):
self.label.move(self.label.pos() + QPoint(15, 0))
def move_down(self):
self.label.move(self.label.pos() + QPoint(0, 15))
if __name__ == "__main__":
app = QApplication(sys.argv)
ex = Example()
ex.show()
sys.exit(app.exec_())

pyqt5 - items in QHBoxLayout overlap?

I've seen several similar questions on items overlapping in (py)Qt, but I cannot for the life of me figure out why I get these overlapping elements (label and slider) inside a QHBoxLayout:
... with this code:
import sys
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *
class Example(QWidget):
def __init__(self):
super(Example, self).__init__()
self.initUI()
#pyqtSlot()
def onclick(self):
print("AAA")
# QApplication.processEvents()
setstr = ""
if self.btn_yrange.isChecked(): setstr = "yrange auto ON"
else: setstr = "yrange auto OFF"
self.btn_yrange.setText(setstr)
#self.btn_yrange.adjustSize()
def initUI(self):
self.col = QColor(0, 0, 0)
self.slider_hbox = QHBoxLayout()
self.btn_yrange = QPushButton('yrange auto OFF', self)
self.btn_yrange.setCheckable(True)
self.btn_yrange.clicked.connect(self.onclick)
self.slider_yrange = QSlider(Qt.Horizontal, self)
self.slider_yrange.setFocusPolicy(Qt.StrongFocus)
self.slider_yrange.setTickPosition(QSlider.TicksBothSides)
self.slider_yrange.setTickInterval(10)
self.slider_yrange.setSingleStep(1)
self.slider_hbox.addStretch(1)
self.slider_hbox.addWidget(self.btn_yrange, Qt.AlignRight)
self.slider_hbox.addStretch(1)
self.slider_hbox.addSpacing(10)
self.slider_hbox.addWidget(self.slider_yrange)
self.slider_hbox.addStretch(1)
self.setGeometry(300, 300, 280, 170)
self.setWindowTitle('Toggle button')
self.show()
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())
How do I force the label and the slider to be side-by-side?
Ok, got it - I saw http://zetcode.com/gui/pyqt5/layout/ - and realized, I had forgotten to add self.setLayout(self.slider_hbox) before self.setGeometry. So, now I get this:
... with this code:
import sys
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *
class Example(QWidget):
def __init__(self):
super(Example, self).__init__()
self.initUI()
#pyqtSlot()
def onclick(self):
print("AAA")
# QApplication.processEvents()
setstr = ""
if self.btn_yrange.isChecked(): setstr = "yrange auto ON"
else: setstr = "yrange auto OFF"
self.btn_yrange.setText(setstr)
#self.btn_yrange.adjustSize()
def initUI(self):
self.col = QColor(0, 0, 0)
self.slider_hbox = QHBoxLayout()
self.btn_yrange = QPushButton('yrange auto OFF', self)
self.btn_yrange.setCheckable(True)
#btn_yrange.move(10, 10)
#self.btn_yrange.clicked.connect(self.onclick)
self.btn_yrange.clicked.connect(self.onclick)
self.slider_yrange = QSlider(Qt.Horizontal, self)
self.slider_yrange.setFocusPolicy(Qt.StrongFocus)
self.slider_yrange.setTickPosition(QSlider.TicksBothSides)
self.slider_yrange.setTickInterval(10)
self.slider_yrange.setSingleStep(1)
#self.slider_hbox.addStretch(1)
self.slider_hbox.addWidget(self.btn_yrange, Qt.AlignRight)
#self.slider_hbox.addStretch(1)
self.slider_hbox.addSpacing(10)
self.slider_hbox.addWidget(self.slider_yrange)
#self.slider_hbox.addStretch(1)
self.setLayout(self.slider_hbox)
self.setGeometry(300, 300, 280, 170)
self.setWindowTitle('Toggle button')
self.show()
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())

Updating slider value constantly crashes program

Maybe I'm doing this completely wrong here, I'm trying to make the "timeline" for an mp3 player. Everything works and I've tried to set the slider to one value and it was fine. My problem is when I try updating the timeline as it keeps on freezing the program and it doesn't unfreeze. Here's my code, I commented out where to start looking at in terms of where I'm having trouble in:
import sys
from PyQt5.QtCore import QCoreApplication, Qt
from PyQt5.QtGui import *
from PyQt5.QtWidgets import QApplication, QWidget, QMainWindow, QPushButton,
QSlider
import vlc
player = vlc.MediaPlayer("/songs/Immigrant Song.mp3")
class window(QMainWindow):
def __init__(self):
super(window, self).__init__()
self.setGeometry(50, 50, 400, 200)
self.setWindowTitle('SlugPlayer')
#self.setWindowIcon(QIcon('pic.png'))
self.home()
def home(self):
playing = 0
btn = QPushButton('quit', self)
btn.clicked.connect(self.close_application)
btn.resize(btn.sizeHint()) #set to acceptable size automatic
btn.move(0, 0)
playbtn = QPushButton('Play', self)
# playbtn.clicked.connect(self.update_bar, playing)
playbtn.clicked.connect(self.play_music, playing)
playbtn.resize(playbtn.sizeHint())
playbtn.move(100, 0)
psebtn = QPushButton('Pause', self)
psebtn.clicked.connect(self.pause_music, playing)
psebtn.resize(psebtn.sizeHint())
psebtn.move(200, 0)
stopbtn = QPushButton('Stop', self)
stopbtn.clicked.connect(self.stop_music, playing)
stopbtn.resize(stopbtn.sizeHint())
stopbtn.move(300, 0)
self.sl = QSlider(Qt.Horizontal, self)
self.sl.setFocusPolicy(Qt.NoFocus)
self.sl.setGeometry(30, 50, 300, 20)
self.sl.setMinimum(0)
self.sl.setMaximum(100)
self.sl.setValue(0)
self.sl.move(50, 100)
# self.sl.valueChanged[int].connect(self.print_value)
self.show()
def close_application(self):
sys.exit()
#here is where I'm trying to update the bar
def play_music(self, playing):
player.play()
playing = 1
while playing == 1:
self.update_bar(playing)
def pause_music(self, playing):
player.pause()
playing = 0
def stop_music(self, playing):
player.stop()
playing = 0
def print_value(self, value):
print(value)
#function to update the bar (converts to an int)
def update_bar(self, playing):
self.sl.setValue(int(player.get_position() * 100))
def run():
app = QApplication(sys.argv)
Gui = window()
sys.exit(app.exec_())
run()
An infinite loop like while playing == 1 freezes the GUI since it does not allow you to do other tasks, in these cases it is better to use a QTimer. Going a little further to the bottom of the problem I have implemented a class that is in charge of managing the player by sending signals when necessary.
import sys
from PyQt5 import QtCore, QtGui, QtWidgets
import vlc
class VLCManager(QtCore.QObject):
durationChanged = QtCore.pyqtSignal(int)
positionChanged = QtCore.pyqtSignal(int)
def __init__(self, parent=None):
super(VLCManager, self).__init__(parent)
self._player = vlc.MediaPlayer()
self._timer = QtCore.QTimer(self, interval=100, timeout=self.update_values)
def setFileName(self, filename):
self._player = vlc.MediaPlayer(filename)
def position(self):
self.durationChanged.emit(self.duration())
return self._player.get_time()
def setPosition(self, time):
if self.position() != time:
self._player.set_time(time)
#QtCore.pyqtSlot()
def update_values(self):
self.positionChanged.emit(self.position())
def duration(self):
return self._player.get_length()
#QtCore.pyqtSlot()
def play(self):
self._player.play()
self.update_values()
self._timer.start()
#QtCore.pyqtSlot()
def pause(self):
self._player.pause()
self.update_values()
self._timer.stop()
#QtCore.pyqtSlot()
def stop(self):
self._player.stop()
self.update_values()
self._timer.stop()
class window(QtWidgets.QMainWindow):
def __init__(self):
super(window, self).__init__()
self._manager = VLCManager(self)
self._manager.setFileName("/songs/Immigrant Song.mp3")
self.setWindowTitle('SlugPlayer')
self.home()
def home(self):
quitbtn = QtWidgets.QPushButton('quit')
quitbtn.clicked.connect(self.close)
playbtn = QtWidgets.QPushButton('Play')
playbtn.clicked.connect(self._manager.play)
psebtn = QtWidgets.QPushButton('Pause', self)
psebtn.clicked.connect(self._manager.pause)
stopbtn = QtWidgets.QPushButton('Stop', self)
stopbtn.clicked.connect(self._manager.stop)
self.sl = QtWidgets.QSlider(orientation=QtCore.Qt.Horizontal)
self.sl.setFocusPolicy(QtCore.Qt.NoFocus)
self._manager.durationChanged.connect(self.sl.setMaximum)
self._manager.positionChanged.connect(self.sl.setValue)
central_widget = QtWidgets.QWidget()
self.setCentralWidget(central_widget)
lay = QtWidgets.QVBoxLayout(central_widget)
hlay = QtWidgets.QHBoxLayout()
for b in (quitbtn, playbtn, psebtn, stopbtn, ):
hlay.addWidget(b)
lay.addLayout(hlay)
lay.addWidget(self.sl)
self.sl.valueChanged[int].connect(self._manager.setPosition)
self.show()
def run():
app = QtWidgets.QApplication(sys.argv)
Gui = window()
sys.exit(app.exec_())
run()

PyQt - Custom scrolling with QListWidget

I am trying to figure out a way to customize the scrollbars for QListWidget to have the scrollbars above and below the QListWidget instead of the normal vertical and horizontal scrollbars.
Please check out my example below if you don't understand what I mean.
In the example below I use QPushButtons with QTimers controlling the scrolling in place of the scrollbars but what I am looking for are scrollbars like the ones in QMenu when menu scrolling is enabled.
If that is not an option, I am wondering if there is a scrollbar signal or something that I could try to use to know when the scrollbars are normally activated? That way I can show/hide the buttons as needed. Thanks.
import sys
from PyQt5.QtCore import pyqtSignal, QTimer, Qt
from PyQt5.QtGui import QPainter
from PyQt5.QtWidgets import QWidget, QPushButton, QVBoxLayout, \
QApplication, QStyle, QListWidget, QStyleOptionButton, QListWidgetItem
class UpBtn(QPushButton):
mouseHover = pyqtSignal()
def __init__(self):
QPushButton.__init__(self)
self.setMouseTracking(True)
self.timer = QTimer()
def paintEvent(self, event):
painter = QPainter()
painter.begin(self)
opt = QStyleOptionButton()
self.initStyleOption(opt)
self.style().drawControl(QStyle.CE_ScrollBarSubLine, opt, painter, self)
painter.end()
def startScroll(self):
self.mouseHover.emit()
def enterEvent(self, event):
self.timer.timeout.connect(self.startScroll)
self.timer.start(120)
def leaveEvent(self, event):
self.timer.stop()
class DwnBtn(QPushButton):
mouseHover = pyqtSignal()
def __init__(self):
QPushButton.__init__(self)
self.setMouseTracking(True)
self.timer = QTimer()
def paintEvent(self, event):
painter = QPainter()
painter.begin(self)
opt = QStyleOptionButton()
self.initStyleOption(opt)
self.style().drawControl(QStyle.CE_ScrollBarAddLine, opt, painter, self)
painter.end()
def startScroll(self):
self.mouseHover.emit()
def enterEvent(self, event):
self.timer.timeout.connect(self.startScroll)
self.timer.start(120)
def leaveEvent(self, event):
self.timer.stop()
class Window(QWidget):
def __init__(self):
super(Window, self).__init__()
self.layout = QVBoxLayout()
self.layout.setContentsMargins(0, 0, 0, 0)
self.layout.setSpacing(0)
self.upBtn = UpBtn()
self.upBtn.setFixedWidth(230)
self.layout.addWidget(self.upBtn)
self.listWidget = QListWidget()
self.listWidget.setFixedWidth(230)
self.listWidget.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
self.listWidget.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
self.layout.addWidget(self.listWidget)
self.downBtn = DwnBtn()
self.downBtn.setFixedWidth(230)
self.layout.addWidget(self.downBtn)
self.setLayout(self.layout)
self.upBtn.clicked.connect(self.upBtnClicked)
self.upBtn.mouseHover.connect(self.upBtnClicked)
self.downBtn.clicked.connect(self.downBtnClicked)
self.downBtn.mouseHover.connect(self.downBtnClicked)
for i in range(100):
item = QListWidgetItem()
item.setText("list item " + str(i))
self.listWidget.addItem(item)
def upBtnClicked(self):
cur = self.listWidget.currentRow()
self.listWidget.setCurrentRow(cur - 1)
def downBtnClicked(self):
cur = self.listWidget.currentRow()
self.listWidget.setCurrentRow(cur + 1)
if __name__ == '__main__':
app = QApplication(sys.argv)
window = Window()
window.show()
sys.exit(app.exec_())
EDIT:
Here is an example image for what I am talking about. This is a scrollable QMenu.
EDIT:
Scrollable QMenu code.
Uncomment the commented parts to get a fixed size like in the image. Normally Qmenu scrolling only works when the menu items exceed the screen height. I am just looking for the top and bottom hover style scrolling but to be used in QListWidget.
import sys
from PyQt5.QtCore import QPoint, QEvent
from PyQt5.QtWidgets import QWidget, QPushButton, QVBoxLayout, \
QApplication, QAction, QMenu, QProxyStyle, QStyle
class MyMenu(QMenu):
def event(self, event):
if event.type() == QEvent.Show:
self.move(self.parent().mapToGlobal(QPoint(-108, 0)))
return super(MyMenu, self).event(event)
# class CustomStyle(QProxyStyle):
# def pixelMetric(self, QStyle_PixelMetric, option=None, widget=None):
# if QStyle_PixelMetric == QStyle.PM_MenuScrollerHeight:
# return 15
# if QStyle_PixelMetric == QStyle.PM_MenuDesktopFrameWidth:
# return 290
# else:
# return QProxyStyle.pixelMetric(self, QStyle_PixelMetric, option, widget)
class MainWindow(QWidget):
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
self.layout = QVBoxLayout()
self.btn = QPushButton("Button")
self.btn.setFixedHeight(30)
self.btn.setFixedWidth(100)
self.myMenu = MyMenu("Menu", self.btn)
self.btn.setMenu(self.myMenu)
self.layout.addWidget(self.btn)
self.setLayout(self.layout)
menus = []
for _ in range(5):
myMenus = QMenu("Menu"+str(_+1), self.btn)
# myMenus.setFixedHeight(120)
myMenus.setStyleSheet("QMenu{menu-scrollable: 1; }")
menus.append(myMenus)
for i in menus:
self.btn.menu().addMenu(i)
for item in range(100):
action = QAction("item" + str(item), self)
i.addAction(action)
if __name__ == '__main__':
app = QApplication(sys.argv)
# app.setStyle(CustomStyle())
w = MainWindow()
w.show()
app.exec_()
The idea is to obtain the row of the upper and lower element that will decide whether the buttons are hidden or not, for that we use the method itemAt () that returns the item given the geometrical coordinates. On the other hand I have improved this calculation has to do every time they change the number of items in the QListView for that we use the signals of the internal model.
import sys
from PyQt5 import QtCore, QtGui, QtWidgets
class Button(QtWidgets.QPushButton):
moveSignal = QtCore.pyqtSignal()
def __init__(self, *args, **kwargs):
super(Button, self).__init__(*args, **kwargs)
self.m_timer = QtCore.QTimer(self, interval=120)
self.m_timer.timeout.connect(self.moveSignal)
self.setMouseTracking(True)
self.setFixedHeight(20)
def mouseReleaseEvent(self, e):
super(Button, self).mousePressEvent(e)
self.setDown(True)
def enterEvent(self, e):
self.setDown(True)
self.m_timer.start()
super(Button, self).enterEvent(e)
def leaveEvent(self, e):
self.setDown(False)
self.m_timer.stop()
super(Button, self).leaveEvent(e)
class Window(QtWidgets.QWidget):
def __init__(self):
super(Window, self).__init__()
self.setFixedWidth(230)
icon = self.style().standardIcon(QtWidgets.QStyle.SP_ArrowUp)
self.upBtn = Button(icon=icon)
self.upBtn.moveSignal.connect(self.moveUp)
icon = self.style().standardIcon(QtWidgets.QStyle.SP_ArrowDown)
self.downBtn = Button(icon=icon)
self.downBtn.moveSignal.connect(self.moveDown)
self.listWidget = QtWidgets.QListWidget()
self.listWidget.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
self.listWidget.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
layout = QtWidgets.QVBoxLayout(self)
layout.setContentsMargins(0, 0, 0, 0)
layout.setSpacing(0)
layout.addWidget(self.upBtn)
layout.addWidget(self.listWidget)
layout.addWidget(self.downBtn)
self.adjust_buttons()
self.create_connections()
def create_connections(self):
self.listWidget.currentItemChanged.connect(self.adjust_buttons)
model = self.listWidget.model()
model.rowsInserted.connect(self.adjust_buttons)
model.rowsRemoved.connect(self.adjust_buttons)
model.rowsMoved.connect(self.adjust_buttons)
model.modelReset.connect(self.adjust_buttons)
model.layoutChanged.connect(self.adjust_buttons)
#QtCore.pyqtSlot()
def adjust_buttons(self):
first = self.listWidget.itemAt(QtCore.QPoint())
r = self.listWidget.row(first)
self.upBtn.setVisible(r != 0 and r!= -1)
last = self.listWidget.itemAt(self.listWidget.viewport().rect().bottomRight())
r = self.listWidget.row(last)
self.downBtn.setVisible( r != (self.listWidget.count() -1) and r != -1)
#QtCore.pyqtSlot()
def moveUp(self):
ix = self.listWidget.moveCursor(QtWidgets.QAbstractItemView.MoveUp, QtCore.Qt.NoModifier)
self.listWidget.setCurrentIndex(ix)
#QtCore.pyqtSlot()
def moveDown(self):
ix = self.listWidget.moveCursor(QtWidgets.QAbstractItemView.MoveDown, QtCore.Qt.NoModifier)
self.listWidget.setCurrentIndex(ix)
#QtCore.pyqtSlot(str)
def add_item(self, text):
item = QtWidgets.QListWidgetItem(text)
self.listWidget.addItem(item)
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
window = Window()
for i in range(100):
window.add_item("item {}".format(i))
window.show()
sys.exit(app.exec_())

Open a new window when the button is clicked || PyQt5

I know this question have been asked multiple times. But I can't understand with the existing examples.
I have a code which creates a window with a button called 'start'. I want the app to close the current window and open a new window when the 'start' button is clicked. The new window has to be a blank window.
Any help is much appreciated.
The code is as follows:
import sys
from PyQt5 import QtGui
from PyQt5.QtWidgets import QApplication, QMainWindow, QPushButton,
QToolTip, QMessageBox, QLabel
class Window(QMainWindow):
def __init__(self):
super().__init__()
self.title = "First Window"
self.top = 100
self.left = 100
self.width = 680
self.height = 500
self.pushButton = QPushButton("Start", self)
self.pushButton.move(275, 200)
self.pushButton.setToolTip("<h3>Start the Session</h3>")
self.main_window()
def main_window(self):
self.label = QLabel("Manager", self)
self.label.move(285, 175)
self.setWindowTitle(self.title)
self.setGeometry(self.top, self.left, self.width, self.height)
self.show()
if __name__ == "__main__":
app = QApplication(sys.argv)
window = Window()
sys.exit(app.exec())
Try it:
import sys
from PyQt5 import QtGui
from PyQt5.QtWidgets import (QApplication, QMainWindow, QPushButton,
QToolTip, QMessageBox, QLabel)
class Window2(QMainWindow): # <===
def __init__(self):
super().__init__()
self.setWindowTitle("Window22222")
class Window(QMainWindow):
def __init__(self):
super().__init__()
self.title = "First Window"
self.top = 100
self.left = 100
self.width = 680
self.height = 500
self.pushButton = QPushButton("Start", self)
self.pushButton.move(275, 200)
self.pushButton.setToolTip("<h3>Start the Session</h3>")
self.pushButton.clicked.connect(self.window2) # <===
self.main_window()
def main_window(self):
self.label = QLabel("Manager", self)
self.label.move(285, 175)
self.setWindowTitle(self.title)
self.setGeometry(self.top, self.left, self.width, self.height)
self.show()
def window2(self): # <===
self.w = Window2()
self.w.show()
self.hide()
if __name__ == "__main__":
app = QApplication(sys.argv)
window = Window()
sys.exit(app.exec())

Categories

Resources