Python, looking to move text from left to right - python

This code moves the text from left to right using PyQt4. My question is, are there other ways to do it?
# -*-coding:utf8 -*-
from PyQt4.QtGui import (QApplication, QGraphicsView, QPainter, QColor, QWidget,
QGraphicsScene, QFont, QLabel, QGraphicsSimpleTextItem,
QBrush, QLinearGradient, QPixmap, QGraphicsTextItem, QPushButton,
QVBoxLayout, QTextDocument)
from PyQt4.QtCore import (QObject, QPointF, QPropertyAnimation,
pyqtProperty, Qt, QAbstractAnimation, QRectF)
import sys
data = [u"I want to make text within an ad bar that moves as there is on the TV screen like this"]
class Text(QObject):
def __init__(self):
super(Text, self).__init__()
doc = QTextDocument("%s" % data[0])
doc.setDefaultStyleSheet(
"body { color : green; background-color : black }")
doc.setDefaultFont(QFont("Times", 20, QFont.Bold))
self.Text_item = QGraphicsTextItem()
self.Text_item.setDocument(doc)
def _set_pos(self, pos):
self.Text_item.setPos(pos)
pos = pyqtProperty(QPointF, fset=_set_pos)
class Example(QGraphicsView):
def __init__(self):
super(Example, self).__init__()
self.initView()
def initView(self):
self.text = Text()
self.anim = QPropertyAnimation(self.text, b"pos")
self.anim.setDuration(19000)
self.anim.setLoopCount(4)
self.anim.setStartValue(QPointF(-1850.0, 450.0))
self.anim.setEndValue(QPointF(800.0, 450.0))
self.scene = QGraphicsScene(self)
self.scene.setSceneRect(0, 0, 300, 300)
self.scene.addItem(self.text.Text_item)
self.setScene(self.scene)
self.setWindowTitle("Text moveing")
self.setRenderHint(QPainter.Antialiasing)
self.anim.start(QAbstractAnimation.DeleteWhenStopped)
if __name__ == '__main__':
app = QApplication(sys.argv)
view = Example()
rect = QApplication.desktop().availableGeometry()
view.resize(int(rect.width() * 0.75), int(rect.height() * 0.9))
view.show()
sys.exit(app.exec_())

Related

Detect Slider move

I want to be able to detect if the slider has moved to a new position and then do some actions in another function called sl. Here is my code:
import sys
from PyQt5 import QtWidgets
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QApplication, QLabel, QLineEdit, QScrollBar, QMainWindow, QMenu, QWidget, QGridLayout, \
QMessageBox, QListWidget, QPlainTextEdit, QTableWidget, QTableWidgetItem, QHeaderView
from PyQt5.QtWidgets import QMenuBar, QHBoxLayout, QVBoxLayout, QSlider, QPushButton, QDial, QBoxLayout, QSpacerItem
from PyQt5.QtGui import QFont, QColor, QPixmap, QResizeEvent, QPen
import PyQt5.QtGui as QtGui
import PyQt5.QtCore as QtCore
class ControlWidget(QWidget):
def __init__(self):
QWidget.__init__(self)
self.layout = QVBoxLayout()
self.layout.setContentsMargins(10, 10, 10, 10)
widget3 = QLabel("Manual")
big_font = QFont('Arial')
big_font.setPointSize(15)
widget3.setFont(big_font)
self.layout.addWidget(widget3, stretch=1)
widget2 = ManualWidget()
self.layout.addWidget(widget2, stretch=4)
self.setLayout(self.layout)
class ManualWidget(QWidget):
def __init__(self):
QWidget.__init__(self)
self.layout = QHBoxLayout()
right_widget = QWidget()
right_layout = QVBoxLayout()
right_top_widget = QWidget()
self.sld1 = self.slider('V1:', 0, 100)
right_top_layout = QVBoxLayout()
right_top_layout.setContentsMargins(0, 0, 0, 0)
right_top_layout.addWidget(self.sld1, stretch=1)
right_top_widget.setLayout(right_top_layout)
right_layout.addWidget(right_top_widget)
right_widget.setLayout(right_layout)
self.layout.addWidget(right_widget, stretch=1)
self.setLayout(self.layout)
self.layout.addWidget(self.name)
self.layout.addWidget(self.label)
self.layout.addWidget(self.slider)
print(self.sl())
def slider(self, name, low, high, step=10):
self.name = QLabel(str(name))
self.label = QLabel(str(low))
self.slider = QSlider(Qt.Horizontal, self)
self.slider.setMinimum(low)
self.slider.setMaximum(high*step)
self.slider.setValue(low)
self.slider.valueChanged.connect(self.change_value)
self.action = False
self.slider.sliderMoved.connect(self.act1)
def change_value(self):
self.set_point = (float(self.slider.value())) / 10
self.label.setText(str(self.set_point))
def act1(self):
self.action = True
return self.action
def sl(self):
if self.action == True:
x = 3
else:
x = 6
return x
class MainWidget(QWidget):
def __init__(self):
QWidget.__init__(self)
self.layout = QVBoxLayout()
self.layout.setContentsMargins(0, 0, 0, 0)
big_font = QFont('Arial')
big_font.setPointSize(10)
bottom_widget = ControlWidget()
self.layout.addWidget(bottom_widget, stretch=10)
self.setLayout(self.layout)
class Window(QMainWindow):
def __init__(self, widget):
QMainWindow.__init__(self)
self.setWindowTitle("Flow test rig")
self.menu = self.menuBar()
self.setCentralWidget(widget)
self.status = self.statusBar()
widget.parent = self
app = QApplication(sys.argv)
main_widget = MainWidget()
win = Window(main_widget)
win.show()
sys.exit(app.exec_())
I tried to detect it with the act1 function, however, self.action is always False, or when it becomes True, it does not reset to False after the first move of the slider. I appreciate it if someone would help me.

Problem integrating QFontComboBox in Qmenu

I'm trying to integrate QFontComboBox within Qmenu.
I try to make two things happen when selecting a particular font from the menu:
The Qmenu will close.
print the selected font.
from PyQt5.QtCore import QObject
from PyQt5.QtGui import QIcon, QFont, QCursor
from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QFontComboBox, QWidgetAction, QMenu, QPushButton
class Window(QWidget):
def __init__(self):
super().__init__()
self.setWindowTitle("Pyside2 FontCombo Box")
self.setGeometry(300,200,300,250)
self.setFontBox()
self.setIcon()
self.show()
def setIcon(self):
appIcon = QIcon("icon.png")
self.setWindowIcon(appIcon)
def setFontBox(self):
self.font_button = QPushButton(self)
self.font_button.setFixedWidth(300)
self.font_button.clicked.connect(lambda: self.setFontmenu())
vbox = QVBoxLayout()
vbox.addWidget(self.font_button)
self.setLayout(vbox)
def setFontmenu(self):
font_menu = QMenu()
font_submenu = QFontComboBox()
font_submenu.setCurrentFont(QFont("Arial"))
objectTest = QObject()
widget = QWidgetAction(objectTest)
widget.setDefaultWidget(font_submenu)
font_menu.addAction(widget)
font_menu.exec_(QCursor.pos())
menu = font_menu
menu.addSeparator()
font_submenu.showPopup()
font_submenu.setFocus()
font_submenu.currentFontChanged.connect(self._changed)
def _changed(self):
font = self.currentFont().family()
print(font)
return
myapp = QApplication(sys.argv)
window = Window()
myapp.exec_()
sys.exit()

How do I open an image in a separate window using a button click in PyQT5?

from PyQt5.QtWidgets import QApplication, QLabel, QWidget, QFileDialog, QPushButton, QLineEdit,QVBoxLayout, QHBoxLayout
from PyQt5.QtCore import *
from PyQt5.QtGui import QPixmap
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QDialog, QVBoxLayout
import Updated_encrypt
import sys
class Window(QWidget):
def __init__(self):
super().__init__()
self.title = 'Encrypt/Decrypt'
self.top = 200
self.left = 500
self.width = 400
self.height = 300
self.InitWindow()
def InitWindow(self):
self.setWindowTitle(self.title)
self.setGeometry(self.left, self.top, self.width, self.height)
vbox = QVBoxLayout()
self.button1 = QPushButton('Encrypt')
self.button1.clicked.connect(self.openSecondDialog)
self.button2 = QPushButton('Decrypt')
vbox.addWidget(self.button1)
vbox.addWidget(self.button2)
self.setLayout(vbox)
self.show()
def openSecondDialog(self):
hbox = QVBoxLayout()
mydialog = QDialog(self)
mydialog.show()
self.button2 = QPushButton('Check Image')
self.button2.clicked.connect(self.getImage)
hbox.addWidget(self.button2)
self.setLayout(hbox)
self.show()
def getImage(self):
hbox = QHBoxLayout()
file_Name = QFileDialog.getOpenFileName(self,
'OpenFile',
'',
'')
image_path = file_Name[0]
updatedImage = Updated_encrypt.decrypt(image_path, 123)
pixmap = QPixmap(updatedImage)
self.label.setPixmap(QPixmap(pixmap))
self.resize(pixmap.width(), pixmap.height())
App = QApplication(sys.argv)
window = Window()
sys.exit(App.exec())
I have my code set up to implement an algorithm to modify an image when my I select it from my pop up dialogue. What I am trying to accomplish is for the image to pop up in a separate window when I click the encrypt button. I can't seem to get anything to pop up in the separate window aside from the window itself. Any help would be appreciated.
You have at least the following errors:
The "hbox" created is being added to the window and not to the QDialog: self.setLayout(hbox), it must be mydialog.setLayout(hbox).
Do not use the same name for 2 different objects as they can cause problems, in your case there are 2 QPushButton assigned to the variable "self.button2".
You try to use the variable "self.label" but never believe it.
Considering the above we can make the following improvements:
Use more descriptive names to easily distinguish their function.
If you are going to have a window that has a different objective, it is better to create a class.
The above avoid the indicated problems, considering the above the solution is:
import sys
from PyQt5.QtGui import QPixmap
from PyQt5.QtWidgets import (
QApplication,
QDialog,
QFileDialog,
QHBoxLayout,
QLabel,
QPushButton,
QVBoxLayout,
QWidget,
)
import Updated_encrypt
class Dialog(QDialog):
def __init__(self, parent=None):
super().__init__(parent)
self.load_image_btn = QPushButton("Check Image")
self.load_image_btn.clicked.connect(self.load_image)
self.image_lbl = QLabel()
lay = QVBoxLayout(self)
lay.addWidget(self.load_image_btn)
lay.addWidget(self.image_lbl)
def load_image(self):
image_path, _ = QFileDialog.getOpenFileName(self, "OpenFile", "", "")
if image_path:
updatedImage = Updated_encrypt.decrypt(image_path, 123)
pixmap = QPixmap(updatedImage)
self.image_lbl.setPixmap(QPixmap(pixmap))
class Window(QWidget):
def __init__(self, parent=None):
super().__init__(parent)
self.title = "Encrypt/Decrypt"
self.InitWindow()
def InitWindow(self):
self.setWindowTitle(self.title)
self.setGeometry(200, 500, 400, 300)
self.encrypt_btn = QPushButton("Encrypt")
self.encrypt_btn.clicked.connect(self.openSecondDialog)
self.decrypt_btn = QPushButton("Decrypt")
vbox = QVBoxLayout(self)
vbox.addWidget(self.encrypt_btn)
vbox.addWidget(self.decrypt_btn)
def openSecondDialog(self):
dialog = Dialog(self)
dialog.show()
if __name__ == "__main__":
app = QApplication(sys.argv)
window = Window()
window.show()
sys.exit(app.exec())

How to add a pixmap drawn in QGraphicsItem to QGraphicsScene? [duplicate]

This question already exists:
How to make the picture zoom (QGraphicsItem), and make scrollbars change their size accordingly (QGraphicsScene)? [duplicate]
Closed 4 years ago.
How to add a pixmap drawn in QGraphicsItem to QGraphicsScene in the following example?
#!/usr/bin/env python
from PyQt5.QtCore import QRectF, Qt
from PyQt5.QtGui import QPixmap
from PyQt5.QtWidgets import QApplication, QGraphicsItem, QGraphicsView, QGraphicsScene, QMainWindow
class TicTacToe(QGraphicsItem):
def __init__(self, helper):
super(TicTacToe, self).__init__()
self.mypixmap = QPixmap("exit.png")
def paint(self, painter, option, widget):
painter.setOpacity(1)
painter.drawPixmap(0,0, 300, 300, self.mypixmap)
def boundingRect(self):
return QRectF(0,0,300,300)
class MyGraphicsView(QGraphicsView):
def __init__(self):
super(MyGraphicsView, self).__init__()
scene = QGraphicsScene(self)
self.tic_tac_toe = TicTacToe(self)
scene.addItem(self.tic_tac_toe)
self.setScene(scene)
self.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOn)
self.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn)
class Example(QMainWindow):
def __init__(self):
super(Example, self).__init__()
self.y = MyGraphicsView()
self.setCentralWidget(self.y)
if __name__ == '__main__':
import sys
app = QApplication(sys.argv)
w = Example()
w.show()
sys.exit(app.exec_())
Try it:
Drag and drop image,
Enlarge Image -> Qt.Key_Right,
Reduce image <- Qt.Key_Left.
from PyQt5.QtCore import (QLineF, QPointF, QRectF,
pyqtSignal, QStandardPaths, Qt)
from PyQt5.QtGui import (QIcon, QBrush, QColor, QPainter, QPixmap)
from PyQt5.QtWidgets import (QAction, QMainWindow, QApplication,
QGraphicsObject,
QGraphicsView, QGraphicsScene, QGraphicsItem,
QGridLayout, QVBoxLayout, QHBoxLayout,
QFileDialog, QLabel, QLineEdit, QPushButton)
from PyQt5.QtOpenGL import QGLFormat
class MyGraphicsView(QGraphicsView):
backgroundColor = QColor(28, 31, 34) # Background color
def __init__(self):
super(MyGraphicsView, self).__init__()
self.resize(800, 600)
self.setBackgroundBrush(self.backgroundColor)
self.setCacheMode(self.CacheBackground)
self.setRenderHints(
QPainter.Antialiasing | QPainter.TextAntialiasing | QPainter.SmoothPixmapTransform)
if QGLFormat.hasOpenGL():
self.setRenderHint(QPainter.HighQualityAntialiasing)
self.setViewportUpdateMode(self.SmartViewportUpdate)
self._scene = QGraphicsScene(-400, -300, 800, 600, self)
self.setScene(self._scene)
self._itemImage = None
def keyReleaseEvent(self, event):
""" Button processing event """
self._scaleImage(event)
super(MyGraphicsView, self).keyReleaseEvent(event)
def closeEvent(self, event):
""" Clear all items in the scene when the window is `closed` """
self._scene.clear()
self._itemImage = None
super(MyGraphicsView, self).closeEvent(event)
def _scaleImage(self, event):
""" Image zoom operation """
if not self._itemImage:
return
scale = self._itemImage.scale()
if event.key() == Qt.Key_Right:
# Enlarge Image -> Qt.Key_Right
if scale >= 0.91:
return
self._itemImage.setScale(scale + 0.1)
elif event.key() == Qt.Key_Left:
# Reduce image <- Qt.Key_Left
if scale <= 0.11:
return
self._itemImage.setScale(scale - 0.1)
def loadImage(self):
path, _ = QFileDialog.getOpenFileName(
self, 'Please select an image',
QStandardPaths.writableLocation(QStandardPaths.DesktopLocation),
'Image(*.jpg *.png)')
if not path:
return
if self._itemImage:
# Delete previous item
self._scene.removeItem(self._itemImage)
del self._itemImage
self._itemImage = self._scene.addPixmap(QPixmap(path))
self._itemImage.setFlag(QGraphicsItem.ItemIsMovable)
self._itemImage.setScale(0.1) # Default load factor
size = self._itemImage.pixmap().size()
# Adjust the image in the middle
self._itemImage.setPos(
-size.width() * self._itemImage.scale() / 2,
-size.height() * self._itemImage.scale() / 2
)
if __name__ == '__main__':
import sys
app = QApplication(sys.argv)
w = MyGraphicsView()
w.show()
ww = QPushButton('Select a file', clicked=w.loadImage)
ww.show()
sys.exit(app.exec_())

adding Image to tab

i have encountered another problem maybe you all could help with i cant seem to add a photo to any of my tabs could you help?
here is my code
import sys
import webbrowser
import random
import time
import os
from PyQt4.QtGui import QApplication, QMainWindow, QPushButton, QWidget, QIcon, QLabel, QPixmap
class UICreator(QWidget): # |||| CREATOR TAB |||
def __init__(self, parent=None):
super(UICreator, self).__init__(parent)
self.Back = QPushButton("<- Back", self)
self.Back.resize(50, 25)
self.Back.move(0, 425)
self.Creator = QPushButton("YouTube", self)
self.Creator.resize(100, 40)
self.Creator.move(25, 50)
self.CreatorB2 = QPushButton("Twitter", self)
self.CreatorB2.resize(100, 40)
self.CreatorB2.move(275, 50)
self.CreatorL = QLabel("Created By: PapaKliffy", self)
self.CreatorL.move(20, 350)
MainWindow here
def startUICreatorTab(self):
self.Creator = UICreator(self)
self.setWindowTitle("Kliffy's SS Tool V2.0 | Creator Tab")
self.setCentralWidget(self.Creator)
self.Creator.Back.clicked.connect(self.startUIWindow)
self.Creator.Creator.clicked.connect(self.Kliffy)
self.Creator.CreatorB2.clicked.connect(self.Kliffy2)
self.show()
You must be override paintEvent
import sys
from PyQt4.QtCore import QSize
from PyQt4.QtGui import QApplication, QPainter, QPixmap, QPushButton, QWidget, QLabel
class UICreator(QWidget): # |||| CREATOR TAB |||
def __init__(self, parent=None):
super(UICreator, self).__init__(parent)
self.resize(QSize(450, 450))
self.Back = QPushButton("<- Back", self)
self.Back.resize(50, 25)
self.Back.move(0, 425)
self.Creator = QPushButton("Youtube", self)
self.Creator.resize(100, 40)
self.Creator.move(50, 50)
self.CreatorB2 = QPushButton("Twitter", self)
self.CreatorB2.resize(100, 40)
self.CreatorB2.move(275, 50)
self.CreatorL = QLabel("Created By: PapaKliffy", self)
self.CreatorL.move(20, 350)
def paintEvent(self, event):
painter = QPainter(self)
painter.drawPixmap(self.rect(), QPixmap("background.jpg"))
if __name__ == '__main__':
app = QApplication(sys.argv)
w = UICreator()
w.show()
sys.exit(app.exec_())
background.png:
Output:

Categories

Resources