I have a program I wrote in VB-6 to emulate an old Timex 2068 Z80 micro.
The display is a direct memory write in a specific area of memory and in VB I look for that range and them use VB-6's PSet to set the pixel(s) in question.
I have been trying to understand the example below..
What I am not understanding is how QPainter interacts and how to call drawpoints() from outside the class with x,y and pen color arguments.
Everything I have tried ends up with a QPainter is not active error...
Any assistance would be appreciated as I've spent hours trying this that and the other thing, to no avail.
Thanks
import sys, random
from PyQt4 import QtGui, QtCore
class Example(QtGui.QWidget):
def __init__(self):
super(Example, self).__init__()
self.initUI()
def initUI(self):
self.setGeometry(300, 300, 280, 170)
self.setWindowTitle('Points')
self.show()
def paintEvent(self, e):
qp = QtGui.QPainter()
qp.begin(self)
self.drawPoints(qp)
qp.end()
def drawPoints(self, qp):
qp.setPen(QtCore.Qt.red)
size = self.size()
for i in range(1000):
x = random.randint(1, size.width()-1)
y = random.randint(1, size.height()-1)
qp.drawPoint(x, y)
def main():
app = QtGui.QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())
Related
I'm new to pyqt6 and even to python. As the title indicates, I got stuck with handling mouse position variables. I was expecting to show coodinates of mouse pointer in the QLabel correspond to the mouse movement. I was able to fetch coordinates from mouseMoveEvent in the QGraphicsScene class to getPosition in the Window class. But, that coodinates couldn't be passed to the other function in Window class.
Here is my code so far.
import sys
from PyQt6 import QtWidgets
from PyQt6.QtWidgets import QVBoxLayout, QWidget, QLabel
class GraphicsScene(QtWidgets.QGraphicsScene):
def __init__(self, parent=None):
super().__init__(parent)
def mouseMoveEvent(self, event):
self.posX = event.scenePos().x()
Window.getPosition(Window, event.scenePos().x())
class GraphicsView(QtWidgets.QGraphicsView):
def __init__(self, parent=None):
super(GraphicsView, self).__init__(parent)
self.setMouseTracking(True)
scene = GraphicsScene(self)
self.setScene(scene)
class Window(QWidget):
def __init__(self):
super().__init__()
self.Layout = QVBoxLayout()
self.gw = GraphicsView() # an image is meant to be set here.
self.Layout.addWidget(self.gw)
self.label = QLabel("Coordinate: x") # wanna show coorinates here correspond to the mouse movement.
self.Layout.addWidget(self.label)
self.setLayout(self.Layout)
def getPosition(self, posX):
self.label.setText("Coordinate: x" + str(self.posX))
self.repaint()
print(posX)
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
w = Window()
w.show()
sys.exit(app.exec())
and got an ERROR like this:
AttributeError: type object 'Window' has no attribute 'label'
It seemas the self in the getPosition function is set to GraphicsScene class after being called (unexpectedly for me). And I have no idea this approach works or not after reading several web documents and asking help for chatGPT. Possibly, I took wrong approach to layout of Widgets.
Any suggestion would be helpful because I'm stuck whole this week with dipression.
Thanks.
Using class Window as parameter to setPosition was wrong, one needs to use an instance of this class. I did this by climbing up the parent() methods and there may be prettier ways to achieve the same. However, it works for now and I did not want to throw in too many changes.
I marked notable changes with comments.
#!/usr/bin/env python3
import sys
from PyQt6 import QtWidgets
class GraphicsScene(QtWidgets.QGraphicsScene):
def __init__(self, parent=None):
super().__init__(parent)
def mouseMoveEvent(self, event):
self.posX = event.scenePos().x()
self.parent().parent().setPosition(event.scenePos().x()) # <-- crawl up the ancestry
class GraphicsView(QtWidgets.QGraphicsView):
def __init__(self, parent=None):
super(GraphicsView, self).__init__(parent)
self.setMouseTracking(True)
scene = GraphicsScene(self)
self.setScene(scene)
class Window(QtWidgets.QWidget):
def __init__(self):
super().__init__()
self.Layout = QtWidgets.QVBoxLayout()
self.gw = GraphicsView(self) # <-- pass self here
self.Layout.addWidget(self.gw)
self.label = QtWidgets.QLabel("Coordinate: x") # wanna show coorinates here correspond to the mouse movement.
self.Layout.addWidget(self.label)
self.setLayout(self.Layout)
def setPosition(self, posX): # <-- this is a setter, not a getter
self.label.setText("Coordinate: x" + str(posX)) # <-- use argument posX
self.repaint()
print(posX)
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
w = Window()
w.show()
sys.exit(app.exec())
Am using pyqt5 and Python in my program which is drawing shapes.
My problem is after am drawing my shapes when I zoom in they look in a really bad way like the image below.
I want to get sharpness like in the SVG image.
So how to get these results in pyqt5?
This what I get:
And this what I want:
from PyQt5.QtWidgets import QWidget, QApplication
from PyQt5.QtGui import QPainter, QPen
from PyQt5.QtCore import Qt
import sys
class Example(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
self.setGeometry(300, 300, 900, 900)
self.setWindowTitle('Pen styles')
self.show()
def paintEvent(self, e):
qp = QPainter()
qp.begin(self)
self.drawLines(qp)
qp.end()
def drawLines(self, qp):
pen = QPen(Qt.black, 2, Qt.SolidLine)
qp.setPen(pen)
qp.drawLine(20, 40, 800, 800)
def main():
app = QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
By default QPainter only uses the TextAntialiasing render hint, so shapes are always aliased.
In order to draw "smooth" lines, you need to activate the Antialiasing hint.
Note that you don't need to call begin() if you provide the paint device in the QPainter constructor, and since it's a local variable in the scope of paintEvent() you don't need to call end() either, as it will be called anyway when the painter is destroyed by the garbage collector when the function returns.
def paintEvent(self, e):
qp = QPainter(self)
qp.setRenderHints(qp.Antialiasing)
self.drawLines(qp)
In PyQt5, I've wrote a GUI. Basically, when a button is pressed, it open a new window, where choose an item from a list. What I want is that after you close the new window, the item you chose appears as text on the first window. It's a hard to explain.
This is the code:
import sys
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QFont
from PyQt5 import QtWidgets
from PyQt5 import QtCore
from PyQt5 import QtGui
class Add(QtWidgets.QMainWindow):
def __init__(self):
super(Add, self).__init__()
#Set The UI
self.initUI()
#Set The GUI Position And Size
self.setGeometry(1050, 500, 400, 50)
#Set The GUI Title
self.setWindowTitle("Add")
def initUI(self):
Central = QtWidgets.QWidget(self)
self.setCentralWidget(Central)
self.deckButton = QtWidgets.QPushButton(self)
self.deckButton.setText("Choose")
self.deckButton.clicked.connect(self.open_deck_browser)
hbox = QtWidgets.QHBoxLayout()
hbox.addWidget(self.deckButton, 1)
Central.setLayout(hbox)
def open_deck_browser(self):
self.w = SetDeck()
self.w.show()
class SetDeck(QtWidgets.QMainWindow):
def __init__(self):
super(SetDeck, self).__init__()
#Set The UI
self.initUI()
#Set The GUI Position And Size
self.setGeometry(200, 200, 800, 640)
#Set The GUI Title
self.setWindowTitle("Choose Deck")
def initUI(self):
widAddToDeckWindow = QtWidgets.QWidget(self)
self.setCentralWidget(widAddToDeckWindow)
#Create The List Widget
self.deckList = QtWidgets.QListWidget()
self.deckList.insertItem(0, "Hello")
self.deckList.insertItem(1, "Hi")
self.deckList.insertItem(2, "Hello There")
self.deckList.item(0).setSelected(True)
self.deckList.itemSelectionChanged.connect(self.show_List)
print([x.row() for x in self.deckList.selectedIndexes()])
#Create The Select Deck Button
self.selectDeck = QtWidgets.QPushButton(self)
self.selectDeck.setText("Choose")
hboxCreateBottomButtons = QtWidgets.QHBoxLayout()
hboxCreateBottomButtons.addStretch()
hboxCreateBottomButtons.addWidget(self.selectDeck)
#Create The Main VBox
vboxMain = QtWidgets.QVBoxLayout()
vboxMain.addWidget(self.deckList)
vboxMain.addLayout(hboxCreateBottomButtons)
widAddToDeckWindow.setLayout(vboxMain)
def show_List(self):
print(repr(self.deckList.selectedItems()[0].text()))
def window():
app = QtWidgets.QApplication(sys.argv)
win = Add()
win.show()
sys.exit(app.exec_())
window()
I've tried using global variables, but it didn't work.
First of all, I recommend you improve your style when naming variables as they make reading easier, for example that the class name are nouns and not a verb.
Getting to the bottom of the problem, never use (or try to use) global variables as they cause silent bugs if there is a better option and you don't understand how it works. In the case that you want a window where you ask the user to provide information on how to select an option that will then be used in the main window then it is advisable to use a QDialog. In the following example, this is done and the "Choose" button is linked to the accept slot so that it closes the window, and that information can be used to know that the "x" button of the window was not closed. Also I have created a property that has the selected text.
import sys
from PyQt5 import QtCore, QtGui, QtWidgets
class MainWindow(QtWidgets.QMainWindow):
def __init__(self):
super(MainWindow, self).__init__()
self.initUI()
self.setGeometry(1050, 500, 400, 50)
self.setWindowTitle("Add")
def initUI(self):
central = QtWidgets.QWidget(self)
self.setCentralWidget(central)
self.deckButton = QtWidgets.QPushButton()
self.deckButton.setText("Choose")
self.deckButton.clicked.connect(self.open_deck_browser)
box = QtWidgets.QVBoxLayout(central)
box.addWidget(self.deckButton)
self.label = QtWidgets.QLabel()
box.addWidget(self.label)
self.label.hide()
def open_deck_browser(self):
dialog = DeckDialog()
if dialog.exec_() == QtWidgets.QDialog.Accepted:
self.label.show()
self.label.setText(dialog.selected_text)
class DeckDialog(QtWidgets.QDialog):
def __init__(self):
super(DeckDialog, self).__init__()
self.initUI()
self.setGeometry(200, 200, 800, 640)
self.setWindowTitle("Choose Deck")
def initUI(self):
self.deckList = QtWidgets.QListWidget()
self.deckList.insertItem(0, "Hello")
self.deckList.insertItem(1, "Hi")
self.deckList.insertItem(2, "Hello There")
self.deckList.item(0).setSelected(True)
self.selectDeck = QtWidgets.QPushButton(self)
self.selectDeck.setText("Choose")
hboxCreateBottomButtons = QtWidgets.QHBoxLayout()
hboxCreateBottomButtons.addStretch()
hboxCreateBottomButtons.addWidget(self.selectDeck)
vboxMain = QtWidgets.QVBoxLayout(self)
vboxMain.addWidget(self.deckList)
vboxMain.addLayout(hboxCreateBottomButtons)
self.selectDeck.clicked.connect(self.accept)
#property
def selected_text(self):
items = self.deckList.selectedItems()
if items:
return items[0].text()
return ""
def main():
app = QtWidgets.QApplication(sys.argv)
win = MainWindow()
win.show()
sys.exit(app.exec_())
if __name__ == "__main__":
main()
I have created a square at random position in canvas, but I don't know how do I move it to somewhere else in canvas by dragging it to desired position, please suggest some edits or a new method to achieve the proposed task, I am learning while doing so.
P.S. Attached a screenshot of the output window.
import sys
from random import randint
from PyQt5 import QtWidgets
from PyQt5.QtWidgets import QApplication, QMainWindow,QPushButton,QWidget
from PyQt5 import QtGui
from PyQt5.QtCore import QRect,Qt
from PyQt5.QtGui import QPainter,QBrush, QPen
from PyQt5 import QtCore
class Window(QMainWindow):
def __init__(self):
super(Window,self).__init__()
title="TeeSquare"
left=500
top=200
width=500
height=400
iconName="square.jpg"
self.setWindowTitle(title)
self.setWindowIcon(QtGui.QIcon(iconName))
self.setGeometry(left, top, width, height)
self.should_paint_Rect = False
self.windowcomponents()
self.initUI()
self.show()
def initUI(self):
if self.should_paint_Rect:
self.label=QtWidgets.QLabel(self)
self.label.setText("circle")
def windowcomponents(self):
button=QPushButton("Add", self)
button.setGeometry(QRect(0, 0, 50, 28))
button.setIcon(QtGui.QIcon("Add.png"))
button.setToolTip("Create Square")
button.clicked.connect(self.paintRect)
def paintEvent(self, event):
super().paintEvent(event)
if self.should_paint_Rect:
painter = QtGui.QPainter(self)
painter.setRenderHint(QPainter.Antialiasing)
painter.setPen(QPen(Qt.black, 5, Qt.SolidLine))
painter.drawRect(randint(0,500), randint(0,500), 100, 100)
self.initUI()
self.label.move(60,100)
def paintRect(self, painter):
self.should_paint_Rect = True
self.update()
app = QApplication(sys.argv)
Rect=Window()
Rect.show()
sys.exit(app.exec_())
The logic of creating a dynamic element is to indicate a set of specific characteristics that by modifying these, the element is modified.
In this case you could use the center of the square, the dimensions of the square, etc. and that data must be implemented through a data structure that can be created from scratch for example by creating a class that has the information of the rectangle, but in Qt it is not necessary to create that element since it already exists and is QRect.
Now that that element has been identified, you can create a QRect whose top-left is random when the button is pressed, and use that QRect to paint it.
For dragging the procedure is:
Get the mouse click position.
Verify that the click is inside the rectangle.
Calculate the position relative to the rectangle.
When moving the mouse, the position of the rectangle must be updated based on the position of the mouse press.
Considering all of the above, the solution is:
import random
import sys
from PyQt5 import QtCore, QtGui, QtWidgets
class Window(QtWidgets.QMainWindow):
def __init__(self):
super(Window, self).__init__()
self.rect = QtCore.QRect()
self.drag_position = QtCore.QPoint()
button = QtWidgets.QPushButton("Add", self)
button.clicked.connect(self.on_clicked)
self.resize(640, 480)
#QtCore.pyqtSlot()
def on_clicked(self):
if self.rect.isNull():
self.rect = QtCore.QRect(
QtCore.QPoint(*random.sample(range(200), 2)), QtCore.QSize(100, 100)
)
self.update()
def paintEvent(self, event):
super().paintEvent(event)
if not self.rect.isNull():
painter = QtGui.QPainter(self)
painter.setRenderHint(QtGui.QPainter.Antialiasing)
painter.setPen(QtGui.QPen(QtCore.Qt.black, 5, QtCore.Qt.SolidLine))
painter.drawRect(self.rect)
def mousePressEvent(self, event):
if self.rect.contains(event.pos()):
self.drag_position = event.pos() - self.rect.topLeft()
super().mousePressEvent(event)
def mouseMoveEvent(self, event):
if not self.drag_position.isNull():
self.rect.moveTopLeft(event.pos() - self.drag_position)
self.update()
super().mouseMoveEvent(event)
def mouseReleaseEvent(self, event):
self.drag_position = QtCore.QPoint()
super().mouseReleaseEvent(event)
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
Rect = Window()
Rect.show()
sys.exit(app.exec_())
I would like to place a phonon videowidget onto a qgraphicsscene so I can overlay graphics etc. When I run the following I get the sound, but no video playing on the qgraphicsview. Help would be appreciated as I thought I was doing as the examples show. However, I suspect its something in how I have understood videoplayer and videowidget.
For testing I am just playing a video straight from a file.
from PySide import QtGui, QtCore
from PySide.phonon import Phonon
from window import Ui_MainWindow # main GUI window
import os, sys
class DiagramScene(QtGui.QGraphicsScene):
InsertItem, InsertLine, InsertText, MoveItem = range(4)
def __init__(self):
super(DiagramScene, self).__init__()
self.myLineColor = QtCore.Qt.black
self.myMode = "Start"
self.line = None
def mousePressEvent(self, mouseEvent):
if (mouseEvent.button() == QtCore.Qt.LeftButton):
if self.myMode == "Start":
self.line = QtGui.QGraphicsLineItem(QtCore.QLineF(mouseEvent.scenePos(), mouseEvent.scenePos()))
self.addItem(self.line)
elif (mouseEvent.button() == QtCore.Qt.RightButton):
self.addText("Hello")
super(DiagramScene, self).mousePressEvent(mouseEvent)
def mouseMoveEvent(self, mouseEvent):
if self.line:
newLine = QtCore.QLineF(self.line.line().p1(), mouseEvent.scenePos())
self.line.setLine(newLine)
def mouseReleaseEvent(self, mouseEvent):
self.line = None
super(DiagramScene, self).mouseReleaseEvent(mouseEvent)
class QPlayer(QtGui.QWidget):
def __init__(self):
super(QPlayer, self).__init__()
media_src = Phonon.MediaSource("C:\Users\Public\Videos\Sample Videos\Wildlife.wmv")
self.audioOuptut=Phonon.AudioOutput(Phonon.MusicCategory, self)
self.player=Phonon.MediaObject(self)
self.player.setCurrentSource(media_src)
Phonon.createPath(self.player, self.audioOuptut)
self.videoWidget=Phonon.VideoWidget(self)
self.videoWidget.FitInView
Phonon.createPath(self.player, self.videoWidget)
self.player.play()
class Main(QtGui.QMainWindow):
def __init__(self):
super(Main, self).__init__()
self.ui=Ui_MainWindow()
self.ui.setupUi(self)
self.scene = DiagramScene()
self.scene.addWidget(QPlayer())
self.gview = self.ui.gView
self.gview.setScene(self.scene)
def main():
app = QtGui.QApplication(sys.argv)
window=Main()
window.show()
sys.exit(app.exec_())
if __name__ == "__main__":
main()
Ok - think I've sorted it (to an extent). Simple case of:
self.videoWidget.setMinimumSize(640,480)
The video doesn't really run very well - breaks up a lot but at least I can draw on it :)