Can someone me explane how should like my code, or what I'm doing wrong ?
I want to use button 'btn_run' to run 'view_splash' function. But somethink going wrong, but 'view_splash' won't start. It show me no errors.
import sys
from PyQt4 import QtGui, QtCore
import time
class Window(QtGui.QMainWindow):
def __init__(self):
super(Window, self).__init__()
self.setGeometry(500, 150, 500, 600)
self.setWindowTitle('Test GUI')
self.threadclass = AThread()
self.connect(self.threadclass, QtCore.SIGNAL("view_splash()"), self.view_splash)
self.home()
def home(self):
btn_run = QtGui.QPushButton("Run", self)
self.threadclass = AThread()
btn_run.clicked.connect(self.threadclass.start)
btn_run.resize(120, 40)
btn_run.move(190, 540)
self.show()
def view_splash(self):
print('test')
label = QLabel("<font color=red size=10<b>" + "SPLASH" + "</b></font>")
label.setWindowFlags(Qt.SplashScreen | Qt.WindowStaysOnTopHint)
label.show()
QtCore.QTimer.singleShot(5000, label.close)
class AThread(QtCore.QThread):
def __init__(self):
super(AThread, self).__init__()
def run(self):
print(1)
print(2)
time.sleep(5)
print(3)
print(4)
self.emit(QtCore.SIGNAL("view_splash()"))
app = QtGui.QApplication(sys.argv)
GUI = Window()
sys.exit(app.exec_())
You need to create and connect the signals differently.
class AThread(QtCore.QThread):
view_splash = QtCore.pyqtSignal()
def run(self):
...
self.view_splash.emit()
class Window(QtGui.QMainWindow):
def __init__(self):
...
self.threadclass.view_splash.connect(self.view_splash)
Related
I would like to capture mouse clicks onto the MainWindow in a child class of the application.
I've tried the following but without success:
import sys
from PyQt5 import QtWidgets, QtGui, QtCore
from abc import ABCMeta, abstractmethod
class BaseView(object):
def __init__(self,parent, page=None):
self.parent = parent
self.page = page
#abstractmethod
def preprare_view(self):
pass
#abstractmethod
def clean_up_view(self):
pass
class FooView(BaseView):
def __init__(self, parent, page):
super(FooView, self).__init__(parent, page)
self.parent = parent
def mousePressEvent(self, QMouseEvent):
print(parent.QMouseEvent.pos())
def mouseReleaseEvent(self, QMouseEvent):
cursor = QtGui.QCursor()
print(parent.cursor.pos())
class Example(QtWidgets.QMainWindow):
def __init__(self):
super(Example, self).__init__()
self.initUI()
def initUI(self):
self.foo = "fooview"
self.Foo = FooView(self,self.foo)
qbtn = QtWidgets.QPushButton('Quit', self)
qbtn.resize(qbtn.sizeHint())
qbtn.move(50, 50)
self.setGeometry(0, 0, 1024, 768)
self.setWindowTitle('Quit button')
self.setWindowFlags(self.windowFlags() | QtCore.Qt.FramelessWindowHint)
self.show()
def main():
app = QtWidgets.QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
I'm wondering how I can capture the mouse clicks in the FooView child class - is that even possible?
There is terminology that the OP uses that is confusing, for example FooView is a child class of BaseView but that has nothing to do with Qt so it is irrelevant for this case so I will omit that class and show the example of how another class can obtain information about the click event of a widget.
The logic is to create a class that inherits from QObject and apply an event filter to the other widget, then override the eventFilter method where the events of the widget are obtained.
import sys
from PyQt5 import QtWidgets, QtGui, QtCore
class MouseObserver(QtCore.QObject):
def __init__(self, widget):
super(MouseObserver, self).__init__(widget)
self._widget = widget
self.widget.installEventFilter(self)
#property
def widget(self):
return self._widget
def eventFilter(self, obj, event):
if obj is self.widget:
if event.type() == QtCore.QEvent.MouseButtonPress:
print(event.pos(), QtGui.QCursor.pos())
elif event.type() == QtCore.QEvent.MouseButtonRelease:
print(event.pos(), QtGui.QCursor.pos())
return super(MouseObserver, self).eventFilter(obj, event)
class Example(QtWidgets.QMainWindow):
def __init__(self):
super(Example, self).__init__()
self.initUI()
def initUI(self):
self.observer = MouseObserver(self)
qbtn = QtWidgets.QPushButton("Quit", self)
qbtn.resize(qbtn.sizeHint())
qbtn.move(50, 50)
self.setGeometry(0, 0, 1024, 768)
self.setWindowTitle("Quit button")
self.setWindowFlags(self.windowFlags() | QtCore.Qt.FramelessWindowHint)
self.show()
def main():
app = QtWidgets.QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())
if __name__ == "__main__":
main()
I have this code:
class Window(QWidget):
def __init__(self):
super().__init__()
self.init_gui()
def init_gui(self):
icon = QtGui.QIcon("icon.png")
button = self.Button(0)
button.set_icon(icon)
button.init()
self.show()
class Button(QToolButton):
def __init__(self, style):
super().__init__()
self.setToolButtonStyle(style)
self.action = QAction()
def set_icon(self, icon):
self.action.setIcon(icon)
def init(self):
self.setDefaultAction(self.action)
Script runs, but it does not show the button.
I think, the button is not child to ### Window object ### parent.
Place button in layout
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
class Window(QWidget):
def __init__(self):
super().__init__()
self.init_gui()
def init_gui(self):
lay = QGridLayout(self) # <---
icon = QIcon("im.png")
button = Button(0)
button.set_icon(icon)
button.init()
lay.addWidget(button) # <---
class Button(QToolButton):
def __init__(self, style):
super().__init__()
self.setToolButtonStyle(style)
self.action = QAction()
def set_icon(self, icon):
self.action.setIcon(icon)
def init(self):
self.setDefaultAction(self.action)
if __name__ == "__main__":
import sys
app = QApplication(sys.argv)
main = Window()
main.show()
sys.exit(app.exec_())
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()
I'm making a small PyQt4 application and so far I have this:
import sys
from PyQt4 import QtGui, QtCore
class Window(QtGui.QWidget):
def __init__(self):
super(Window, self).__init__()
self.initUi()
def initUi(self):
self.setFixedSize(500, 300)
self.text = QtGui.QLabel('Text to be changed')
self.text2 = QtGui.QLabel('Also to be changed')
self.textCheckBox = QtGui.QCheckBox()
self.textCheckBox.stateChanged.connect(self.check(self.text))
self.show()
def check(self, state, theText):
if state == QtCore.Qt.Checked:
theText.setStyleSheet("color: pink")
else:
theText.setStyleSheet("color: black")
def main():
q = QtGui.QApplication(sys.argv)
w = Window()
sys.exit(q.exec())
if __name__=='__main__':
main()
The problem is, my .connect line doesn't seem to want to recognize the parameter I pass into it and I'm not sure why. I can't reference the text directly in the function as I would like to pass many QLabel arguments to it hence I made a theText parameter. I'd appreciate any help.
Version that works without parameters:
import sys
from PyQt4 import QtGui, QtCore
class Window(QtGui.QWidget):
def __init__(self):
super(Window, self).__init__()
self.initUi()
def initUi(self):
self.setFixedSize(500, 300)
self.text = QtGui.QLabel('Text to be changed')
self.text2 = QtGui.QLabel('Also to be changed')
self.textCheckBox = QtGui.QCheckBox()
self.textCheckBox.stateChanged.connect(self.check)
self.hbox = QtGui.QHBoxLayout()
self.hbox.addWidget(self.text)
self.hbox.addWidget(self.textCheckBox)
self.setLayout(self.hbox)
self.show()
def check(self, state):
if state == QtCore.Qt.Checked:
self.text.setStyleSheet("color: pink")
else:
self.text.setStyleSheet("color: black")
def main():
q = QtGui.QApplication(sys.argv)
w = Window()
sys.exit(q.exec())
if __name__=='__main__':
main()
import sys
from PyQt4 import QtGui, QtCore
class Window(QtGui.QWidget):
def __init__(self):
super(Window, self).__init__()
self.initUi()
def initUi(self):
self.setFixedSize(500, 300)
self.text = QtGui.QLabel('Text to be changed')
self.text2 = QtGui.QLabel('Also to be changed')
self.textCheckBox = QtGui.QCheckBox()
test = self.textCheckBox.checkState()
self.textCheckBox.stateChanged.connect(lambda: self.check(self.textCheckBox.checkState(), self.text))
self.hbox = QtGui.QHBoxLayout()
self.hbox.addWidget(self.text)
self.hbox.addWidget(self.textCheckBox)
self.setLayout(self.hbox)
self.show()
def check(self, state, theText):
if state == QtCore.Qt.Checked:
self.setWindowTitle("test")
else:
theText.setStyleSheet("color: black")
def main():
q = QtGui.QApplication(sys.argv)
w = Window()
sys.exit(q.exec())
if __name__=='__main__':
main()
Seem to have fixed it. Not too sure why it works though.
I've recently started learning PyQt on my own and I've come in some trouble trying to write a custom class that inherits from QPushButton so I can adjust its attributes. I'm trying to pass a text as an argument whenever I initialize an object of this class. I am pretty sure there's something wrong with my init but I haven't found it yet.
Here is the code:
import sys
from PySide import QtGui, QtCore
class mainb(QtGui.QPushButton):
def __init__(Text,self, parent = None):
super().__init__(parent)
self.setupbt(Text)
def setupbt(self):
self.setFlat(True)
self.setText(Text)
self.setGeometry(200,100, 60, 35)
self.move(300,300)
print('chegu aqui')
self.setToolTip('Isso é muito maneiro <b>Artur</b>')
self.show()
class mainwindow(QtGui.QWidget):
def __init__(self , parent = None):
super().__init__()
self.setupgui()
def setupgui(self):
self.setToolTip('Oi <i>QWidget</i> widget')
self.resize(800,600)
self.setWindowTitle('Janela do Artur')
af = mainb("Bom dia",self)
self.show()
"""
btn = QtGui.QPushButton('Botão',self)
btn.clicked.connect(QtCore.QCoreApplication.instance().quit)
btn.resize(btn.sizeHint())
btn.move(300, 50)
"""
def main():
app = QtGui.QApplication(sys.argv)
ex = mainwindow()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
You are using super in wrong way, super must get a instance and another thing your first arg is Text, that's wrong that should be self. I fixed some more and the below code should work for you
import sys
from PySide import QtGui, QtCore
class mainb(QtGui.QPushButton):
def __init__(self, Text, parent = None):
super(mainb, self).__init__()
self.setupbt(Text)
def setupbt(self, Text):
self.setFlat(True)
self.setText(Text)
self.setGeometry(200,100, 60, 35)
self.move(300,300)
print('chegu aqui')
self.setToolTip('Isso muito maneiro <b>Artur</b>')
self.show()
class mainwindow(QtGui.QWidget):
def __init__(self , parent = None):
super(mainwindow, self).__init__()
self.setupgui()
def setupgui(self):
self.setToolTip('Oi <i>QWidget</i> widget')
self.resize(800,600)
self.setWindowTitle('Janela do Artur')
newLayout = QtGui.QHBoxLayout()
af = mainb("Bom dia",self)
newLayout.addWidget(af)
self.setLayout(newLayout)
self.show()
def main():
app = QtGui.QApplication(sys.argv)
ex = mainwindow()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
Your def setupbt(self) does not seem to take the text as argument. Try def setupbt(self, Text): instead.