First of all I know this question in general have been asked and solved. I have read the complete post here: PyQt4 - Drag and Drop but my question is a little bit more specific.
What I am creating is the game Draught, but rather simplified. What I currently need help with is moving the pieces. I've managed to create a button which can be moved by holding down the left mouse button. The hard part is implementing this functionality for the button to a piece. The game is using two separate files, one called GUI-game-template and the other Game_Model.
My code so far:
import sys
from PyQt4.QtCore import *
from PyQt4.QtGui import *
import Game_Model
from PyQt4 import QtCore, QtGui
app = QApplication(sys.argv)
class MyGame(QMainWindow):
def __init__(self, parent=None):
super(MyGame, self).__init__()
self.setWindowTitle("Game template")
self.initUI()
self.timer = QBasicTimer()
def initUI(self):
"""Initializing all components"""
self.setAcceptDrops(True)
self.frame = QWidget(self)
self.setCentralWidget(self.frame)
#Hole window
self.layout = QVBoxLayout()
#Widgets
self.gui_board = Game_Model.Game_Model(self)
self.gui_board.setLineWidth(3)
self.gui_board.setFrameStyle(QFrame.Plain)
self.gui_board.setMinimumSize(400,400)
self.layout.addWidget(self.gui_board)
self.gui_board.setFocus()
#Buttons
self.button_box = QHBoxLayout()
self.button_box.addStretch(1)
self.btn_start = QPushButton('Start', self)
self.btn_start.clicked.connect(self.btn_start_action)
self.button_box.addWidget( self.btn_start )
self.btn_restart = QPushButton('Restart', self)
self.btn_restart.clicked.connect(self.btn_restart_action)
self.layout.addLayout(self.button_box)
self.button_box.addWidget( self.btn_restart )
self.button_box.addStretch(1)
self.button = Button('Button', self)
self.button.move(100, 65)
#Add layouts to widget
self.layout.addLayout(self.button_box)
self.frame.setLayout(self.layout)
#Statusbar
self.statusBar().showMessage('Ready')
def keyPressEvent(self, event):
key = Qt.MouseButton()
if(key == Qt.Key_Up):
self.gui_board.hero_y -= 1
if(key == Qt.Key_Down):
self.gui_board.hero_y += 1
if(key == Qt.Key_Left):
self.gui_board.hero_x -= 1
if(key == Qt.Key_Right):
self.gui_board.hero_x += 1
self.update()
def timerEvent(self,event):
if (event.timerId() == self.timer.timerId()):
self.gui_board.enemy_x += 1
self.gui_board.enemy_y += 1
self.update()
def dragEnterEvent(self, e):
e.accept()
def dropEvent(self, e):
position = e.pos()
self.button.move(position)
e.setDropAction(QtCore.Qt.MoveAction)
e.accept()
#pyqtSlot()
def btn_start_action(self):
self.timer.start(500,self)
#pyqtSlot()
def btn_restart_action(self):
pass
def run(self):
self.show()
sys.exit(app.exec_())
class Button(QtGui.QPushButton):
def __init__(self, title, parent):
super(Button,self).__init__(title, parent)
def mouseMoveEvent(self, e):
if e.buttons() != Qt.LeftButton:
return
mimeData = QMimeData()
drag = QtGui.QDrag(self)
drag.setMimeData(mimeData)
drag.setHotSpot(e.pos() - self.rect().topLeft())
dropAction = drag.start(QtCore.Qt.MoveAction)
#Creates an instance and runs it
MyGame().run()
Next file:
from PyQt4.QtCore import *
from PyQt4.QtGui import *
class Game_Model(QFrame):
Boardwidth = 8
Boardheight = 8
def __init__(self,parent):
super(Game_Model, self).__init__()
self.setFocusPolicy(Qt.StrongFocus)
self.hero_x = 2
self.hero_y = 2
self.enemy_x = 1
self.enemy_y = 6
self.enemy_x2 = 2
self.enemy_y2 = 5
self.enemy_x3 = 2
self.enemy_y3 = 7
self.enemy_x4 = 0
self.enemy_y4 = 7
self.enemy_x5 = 0
self.enemy_y5 = 5
self.enemy_x6 = 3
self.enemy_y6 = 6
self.enemy_x7 = 4
self.enemy_y7 = 5
self.enemy_x8 = 4
self.enemy_y8 = 7
self.enemy_x9 = 5
self.enemy_y9 = 6
self.enemy_x10 = 6
self.enemy_y10 = 5
self.enemy_x11 = 6
self.enemy_y11 = 7
self.enemy_x12 = 7
self.enemy_y12 = 6
def paintEvent(self, event):
qp = QPainter()
width = self.size().width() - 1
height = self.size().height() - 1
sq_w = width/Game_Model.Boardwidth
sq_h = height/Game_Model.Boardheight
qp.begin(self)
self.draw_grid(qp, width, height, sq_w, sq_h)
self.draw_hero(qp, sq_w, sq_h)
self.draw_enemy(qp, sq_w, sq_h)
self.draw_enemy2(qp, sq_w, sq_h)
self.draw_enemy3(qp, sq_w, sq_h)
self.draw_enemy4(qp, sq_w, sq_h)
self.draw_enemy5(qp, sq_w, sq_h)
self.draw_enemy6(qp, sq_w, sq_h)
self.draw_enemy7(qp, sq_w, sq_h)
self.draw_enemy8(qp, sq_w, sq_h)
self.draw_enemy9(qp, sq_w, sq_h)
self.draw_enemy10(qp, sq_w, sq_h)
self.draw_enemy11(qp, sq_w, sq_h)
self.draw_enemy12(qp, sq_w, sq_h)
qp.end()
def draw_grid(self, qp, width, height, sq_w, sq_h):
for n in range(0,Game_Model.Boardheight + 1):
qp.drawLine(0,sq_h * n, width, sq_h * n)
for n in range(0,Game_Model.Boardwidth + 1):
qp.drawLine(sq_w * n, 0, sq_w * n, height)
def draw_hero(self, qp, sq_w, sq_h):
color = QColor(0x20FA48)
qp.fillRect( sq_w * self.hero_x + 7, sq_h * self.hero_y + 7,
sq_w * 0.7, sq_h * 0.7, color)
qp.drawRect( sq_w * self.hero_x + 7, sq_h * self.hero_y + 7,
sq_w * 0.7, sq_h * 0.7)
def draw_enemy(self,qp, sq_w, sq_h):
qp.setBrush(QBrush(QColor('red'),Qt.SolidPattern))
qp.drawEllipse( sq_w * self.enemy_x + 7, sq_h * self.enemy_y + 7,
sq_w * 0.7, sq_h * 0.7)
def draw_enemy2(self,qp, sq_w, sq_h):
qp.setBrush(QBrush(QColor('red'),Qt.SolidPattern))
qp.drawEllipse( sq_w * self.enemy_x2 + 7, sq_h * self.enemy_y2 + 7,
sq_w * 0.7, sq_h * 0.7)
def draw_enemy3(self,qp, sq_w, sq_h):
qp.setBrush(QBrush(QColor('red'),Qt.SolidPattern))
qp.drawEllipse( sq_w * self.enemy_x3 + 7, sq_h * self.enemy_y3 + 7,
sq_w * 0.7, sq_h * 0.7)
def draw_enemy4(self,qp, sq_w, sq_h):
qp.setBrush(QBrush(QColor('red'),Qt.SolidPattern))
qp.drawEllipse( sq_w * self.enemy_x4 + 7, sq_h * self.enemy_y4 + 7,
sq_w * 0.7, sq_h * 0.7)
def draw_enemy5(self,qp, sq_w, sq_h):
qp.setBrush(QBrush(QColor('red'),Qt.SolidPattern))
qp.drawEllipse( sq_w * self.enemy_x5 + 7, sq_h * self.enemy_y5 + 7,
sq_w * 0.7, sq_h * 0.7)
def draw_enemy6(self,qp, sq_w, sq_h):
qp.setBrush(QBrush(QColor('red'),Qt.SolidPattern))
qp.drawEllipse( sq_w * self.enemy_x6 + 7, sq_h * self.enemy_y6 + 7,
sq_w * 0.7, sq_h * 0.7)
def draw_enemy7(self,qp, sq_w, sq_h):
qp.setBrush(QBrush(QColor('red'),Qt.SolidPattern))
qp.drawEllipse( sq_w * self.enemy_x7 + 7, sq_h * self.enemy_y7 + 7,
sq_w * 0.7, sq_h * 0.7)
def draw_enemy8(self,qp, sq_w, sq_h):
qp.setBrush(QBrush(QColor('red'),Qt.SolidPattern))
qp.drawEllipse( sq_w * self.enemy_x8 + 7, sq_h * self.enemy_y8 + 7,
sq_w * 0.7, sq_h * 0.7)
def draw_enemy9(self,qp, sq_w, sq_h):
qp.setBrush(QBrush(QColor('red'),Qt.SolidPattern))
qp.drawEllipse( sq_w * self.enemy_x9 + 7, sq_h * self.enemy_y9 + 7,
sq_w * 0.7, sq_h * 0.7)
def draw_enemy10(self,qp, sq_w, sq_h):
qp.setBrush(QBrush(QColor('red'),Qt.SolidPattern))
qp.drawEllipse( sq_w * self.enemy_x10 + 7, sq_h * self.enemy_y10 + 7,
sq_w * 0.7, sq_h * 0.7)
def draw_enemy11(self,qp, sq_w, sq_h):
qp.setBrush(QBrush(QColor('red'),Qt.SolidPattern))
qp.drawEllipse( sq_w * self.enemy_x11 + 7, sq_h * self.enemy_y11 + 7,
sq_w * 0.7, sq_h * 0.7)
def draw_enemy12(self,qp, sq_w, sq_h):
qp.setBrush(QBrush(QColor('red'),Qt.SolidPattern))
qp.drawEllipse( sq_w * self.enemy_x12 + 7, sq_h * self.enemy_y12 + 7,
sq_w * 0.7, sq_h * 0.7)
Related
I'm making a 3d platformer game in ursina and finishing level 1. But I can't get the Player to touch the portal and move to the next level. Also, I'm using my own player controller for some smoother jumping so I can't use intersect. I'll show you my code and the player code:
main.py File:
from ursina import *
from ursina import curve
from player import Player
from ursina.prefabs.sky import Sky
from ursina.shaders import lit_with_shadows_shader
app = Ursina(borderless=False)
window.exit_button.enabled = True
window.cog_button.enabled = True
window.fps_counter.enabled = False
window.exit_button.text = ''
window.exit_button.color = color.gray
window.exit_button.texture = "sword"
window.cog_menu.enabled = False
window.title = 'Urono'
window.icon = 'duh.png'
Sky()
player = Player("cube", (0, 10, 0), "box")
player.SPEED = 3
player.jump_height = 0.5
ground = Entity(model='cube', texture='assets/hrllohrllo', collider='mesh', position=(
0, 0, 0), scale=(7, 2, 7), shader=lit_with_shadows_shader)
FPC_POS = player.position
background = Audio(
'audio/urono-cheerbeat-background',
loop=True,
autoplay=True
)
quM = Audio(
'audio/quit',
loop=False,
autoplay=False
)
grappler = Entity(parent=camera.ui, model='assets/grappler.obj', position=(0.8, -0.4, 0), scale=(0.25, 0.25, 0.25),
color=color.red, texture="white_cube", rotation=(-10, -10, -10), shader=lit_with_shadows_shader, on_click=camera.shake)
lava = Entity(parent=scene, model = "plane", texture = "white_cube", position = (0, -100, 0), scale = (10000, 1, 10000), color = color.orange, collider = "plane")
class Grapple(Button):
def __init__(self, position=(0, 0, 0)):
super().__init__(
parent=scene,
model="cube",
texture="assets/grappler_texture",
collider="box",
position=position,
shader=lit_with_shadows_shader,
scale=(10, 10, 10)
)
self.player = player
def update(self):
self.on_click = Func(self.player.animate_position,
self.position, duration=0.5, curve=curve.linear)
ray = raycast(self.player.position, self.player.forward,
distance=0.5, ignore=[player, ])
if ray.entity == self:
self.player.y += 2
class Portal(Entity):
def __init__(self, position=(0, 0, 0)):
super().__init__(
parent=scene,
model="assets/portal.obj",
scale=(2, 4, 2),
texture="portal_texture",
collider="box",
position=position,
shader=lit_with_shadows_shader
)
self.player = player
def update(self):
if hit.entity == self.player:
level2()
class Platform(Entity):
def __init__(self, position=(0, 0, 0)):
super().__init__(
parent=scene,
model="cube",
scale=(7, 2, 7),
texture="grappler_texture",
collider="box",
position=position,
shader=lit_with_shadows_shader
)
FPC_POS_text = Text("", scale=2, x=0.2, y=0.2)
QUIT_WARN_text = Text("", scale=2, x=0.2, y=0.2)
def level1():
Platform(Vec3(1, -1, -27.2754))
Platform(Vec3(0.0640625, 0.00125, -53.2754))
Platform(Vec3(0.169236, 14.3008, -33.3041))
Platform(Vec3(-0.886462, 7.42754, -73.0878))
Platform(Vec3(-1.10773, 12.6191, -90.2041))
Platform(Vec3(-1.3286, 19.5097, -107.289))
Platform(Vec3(-1.55644, 25.4606, -124.914))
Platform(Vec3(-2.07368, 25.0602, -164.926))
Platform(Vec3(-4.56876, 24.3813, -206.787))
Platform(Vec3(-6.55665, 36.2641, -210.516))
Platform(Vec3(-5.2145, 24.7415, -232.169))
Platform(Vec3(-8.12956, 19.0883, -313.253))
Grapple(Vec3(-7.73628, 24.0123, -262.297))
Platform(Vec3(-8.12433, 26.1495, -245.986))
Platform(Vec3(6.65358, 20.0725, -312.287))
Platform(Vec3(25.9705, 20.3887, -312.661))
Platform(Vec3(44.783, 20.6966, -313.026))
Platform(Vec3(63.9781, 21.0108, -313.399))
Platform(Vec3(106.336, 21.7041, -314.22))
Platform(Vec3(127.271, 22.0467, -314.626))
Platform(Vec3(140.357, 27.1054, -314.879))
Platform(Vec3(155.502, 31.5333, -315.172))
Platform(Vec3(183.088, 32.3551, -313.688))
Platform(Vec3(207.893, 32.8512, -313.688))
Platform(Vec3(272.206, 34.1376, -313.688))
Platform(Vec3(286.402, 40.7493, -313.687))
Platform(Vec3(279.467, 45.2291, -298.974))
Platform(Vec3(276.644, 47.8035, -247.383))
Platform(Vec3(275.481, 47.0466, -206.259))
Portal(Vec3(275.486, 52.046, -206.386))
Platform(Vec3(280.947, 52.4222, -273.657))
Platform(Vec3(-1.45974, 25.976, -178.793))
Platform(Vec3(-2.1425, 25.0246, -178.681))
Platform(Vec3(-1.51808, 25.5806, -140.103))
Platform(Vec3(-2.0098, 26.0397, -150))
Platform(Vec3(-2.38591, 26.2334, -191.67))
Grapple(Vec3(91.2361, 32.216, -313.007))
Platform(Vec3(-9.097, 32.2579, -280.842))
Platform(Vec3(279.779, 52.2863, -288.757))
Platform(Vec3(277.064, 51.1692, -255.344))
Grapple(Vec3(274.925, 56.6227, -223.522))
Platform(Vec3(251.518, 40.172, -314.807))
Platform(Vec3(234.105, 33.5976, -314.413))
Platform(Vec3(225.337, 34.8861, -314.214))
Platform(Vec3(215.52, 33.2659, -316.504))
level1()
def level2():
Platform(Vec3(1, -1, -27.2754))
Platform(Vec3(0.0640625, 0.00125, -53.2754))
def update():
if held_keys['i']:
FPC_POS_text.text = f"{player.position}"
else:
FPC_POS_text.text = ' '
if held_keys['escape']:
if not quM.playing:
quM.play()
QUIT_WARN_text.text = 'Press "q" to quit'
else:
QUIT_WARN_text.text = ' '
if held_keys['q']:
quit()
PointLight(parent=camera, color=color.white, position=(0, 10, -1.5))
AmbientLight(color=color.rgba(100, 100, 100, 0.1))
AmbientLight(parent=lava, color = color.white, position = (0, -50, 0))
app.run()
Then The player File:
from ursina import *
import math
def sign(x): return -1 if x < 0 else (1 if x > 0 else 0)
class Player(Entity):
def __init__(self, model, position, collider, scale=(1, 1, 1), SPEED=3, velocity=(0, 0, 0), MAXJUMP=1, gravity=1, controls="wasd", **kwargs):
super().__init__(
model="cube",
position=position,
scale=(1, 1, 1),
visible_self=False
)
self.collider = BoxCollider(
self, center=Vec3(0, 1, 0), size=Vec3(1, 2, 1))
mouse.locked = True
camera.parent = self
camera.position = (0, 2, 0)
camera.rotation = (0, 0, 0)
camera.fov = 100
self.velocity_x, self.velocity_y, self.velocity_z = velocity
self.SPEED = SPEED
self.MAXJUMP = MAXJUMP
self.jump_count = 0
self.gravity = gravity
self.jump_height = 0.3
self.slope = 40
self.controls = controls
self.sensibility = 70
self.crosshair = Entity(model="quad", color=color.red, parent=camera, position=(
0, 0, 1), scale=(0.01, 0.01, 0.01))
for key, value in kwargs.items():
try:
setattr(self, key, value)
except:
print(key, value)
def jump(self):
self.velocity_y = self.jump_height * 40
self.jump_count += 1
def update(self):
y_movement = self.velocity_y * time.dt
direction = (0, sign(y_movement), 0)
yRay = boxcast(origin=self.world_position, direction=direction,
distance=self.scale_y/2+abs(y_movement), ignore=[self, ])
if yRay.hit:
move = False
self.jump_count = 0
self.velocity_y = 0
else:
self.y += y_movement
self.velocity_y -= self.gravity * time.dt * 25
x_movement = (self.forward[0]*held_keys[self.controls[0]] +
self.left[0]*held_keys[self.controls[1]] +
self.back[0]*held_keys[self.controls[2]] +
self.right[0]*held_keys[self.controls[3]]) * time.dt*6 * self.SPEED
z_movement = (self.forward[2]*held_keys[self.controls[0]] +
self.left[2]*held_keys[self.controls[1]] +
self.back[2]*held_keys[self.controls[2]] +
self.right[2]*held_keys[self.controls[3]]) * time.dt*6 * self.SPEED
if x_movement != 0:
direction = (sign(x_movement), 0, 0)
xRay = boxcast(origin=self.world_position, direction=direction,
distance=self.scale_x/2+abs(x_movement), ignore=[self, ], thickness=(1, 1))
if not xRay.hit:
self.x += x_movement
else:
TopXRay = raycast(origin=self.world_position-(0, self.scale_y/2-.1, 0),
direction=direction, distance=self.scale_x /
2+math.tan(math.radians(self.slope))*.1,
ignore=[self, ])
if not TopXRay.hit:
self.x += x_movement
HeightRay = raycast(origin=self.world_position+(sign(x_movement)*self.scale_x/2, -self.scale_y/2, 0),
direction=(0, 1, 0), ignore=[self, ])
if HeightRay.hit:
self.y += HeightRay.distance
if z_movement != 0:
direction = (0, 0, sign(z_movement))
zRay = boxcast(origin=self.world_position, direction=direction,
distance=self.scale_z/2+abs(z_movement), ignore=[self, ], thickness=(1, 1))
if not zRay.hit:
self.z += z_movement
else:
TopZRay = raycast(origin=self.world_position-(0, self.scale_y/2-.1, 0),
direction=direction, distance=self.scale_z /
2+math.tan(math.radians(self.slope))*.1,
ignore=[self, ])
if not TopZRay.hit:
self.z += z_movement
HeightRay = raycast(origin=self.world_position+(0, -self.scale_y/2, sign(z_movement)*self.scale_z/2),
direction=(0, 1, 0), ignore=[self, ])
if HeightRay.hit:
self.y += HeightRay.distance
camera.rotation_x -= mouse.velocity[1] * self.sensibility
self.rotation_y += mouse.velocity[0] * self.sensibility
camera.rotation_x = min(max(-80, camera.rotation_x), 80)
def input(self, key):
if key == 'space':
if self.jump_count < self.MAXJUMP:
self.jump()
There's no intersecton variable, and I don't know what to do.
Credit to Mandaw for the player.
I have a 2-D numpy array that I have plotted in Pyopengl using Pyqt. Now I want to set The background of the plot greyscale such that when the line moves up or down, its background grey color changes intensity. I am attaching images for the behaviour I want.
but all I am able to create till now is with white background like this
the code that I have written is
import OpenGL.GL as gl
import OpenGL.arrays.vbo as glvbo
from PyQt5.Qt import *
import numpy as np
import sys
VS = '''
#version 450
layout(location = 0) in vec2 position;
uniform float right;
uniform float bottom;
uniform float left;
uniform float top;
void main() {
const float far = 1.0;
const float near = -1.0;
mat4 testmat = mat4(
vec4(2.0 / (right - left), 0, 0, 0),
vec4(0, 2.0 / (top - bottom), 0, 0),
vec4(0, 0, -2.0 / (far - near), 0),
vec4(-(right + left) / (right - left), -(top + bottom) / (top - bottom), -(far + near) / (far - near), 1)
);
gl_Position = testmat * vec4(position.x, position.y, 0., 1.);
}
'''
FS = '''
#version 450
// Output variable of the fragment shader, which is a 4D vector containing the
// RGBA components of the pixel color.
uniform vec3 triangleColor;
out vec4 outColor;
void main()
{
outColor = vec4(triangleColor, 1.0);
}
'''
def compile_vertex_shader(source):
"""Compile a vertex shader from source."""
vertex_shader = gl.glCreateShader(gl.GL_VERTEX_SHADER)
gl.glShaderSource(vertex_shader, source)
gl.glCompileShader(vertex_shader)
# check compilation error
result = gl.glGetShaderiv(vertex_shader, gl.GL_COMPILE_STATUS)
if not (result):
raise RuntimeError(gl.glGetShaderInfoLog(vertex_shader))
return vertex_shader
def compile_fragment_shader(source):
"""Compile a fragment shader from source."""
fragment_shader = gl.glCreateShader(gl.GL_FRAGMENT_SHADER)
gl.glShaderSource(fragment_shader, source)
gl.glCompileShader(fragment_shader)
result = gl.glGetShaderiv(fragment_shader, gl.GL_COMPILE_STATUS)
if not (result):
raise RuntimeError(gl.glGetShaderInfoLog(fragment_shader))
return fragment_shader
def link_shader_program(vertex_shader, fragment_shader):
"""Create a shader program with from compiled shaders."""
program = gl.glCreateProgram()
gl.glAttachShader(program, vertex_shader)
gl.glAttachShader(program, fragment_shader)
gl.glLinkProgram(program)
result = gl.glGetProgramiv(program, gl.GL_LINK_STATUS)
if not (result):
raise RuntimeError(gl.glGetProgramInfoLog(program))
return program
class GLPlotWidget(QGLWidget):
def __init__(self, *args):
super(GLPlotWidget, self).__init__()
self.width, self.height = 100, 100
self.e = np.load('two.npy', mmap_mode='r')
self.vbo = glvbo.VBO(self.e)
self.count = self.vbo.shape[1]
self.right, self.left, self.top, self.bottom = self.e[0, -1, 0].min(), self.e[0, 0, 0].max(), self.e[0, :,
1].max(), self.e[-1,
:,
1].min()
# self.data = np.zeros((10, 2))
self.showMaximized()
def initializeGL(self):
vs = compile_vertex_shader(VS)
fs = compile_fragment_shader(FS)
self.shaders_program = link_shader_program(vs, fs)
def ortho_view(self):
right = gl.glGetUniformLocation(self.shaders_program, "right")
gl.glUniform1f(right, self.right)
left = gl.glGetUniformLocation(self.shaders_program, "left")
gl.glUniform1f(left, self.left)
top = gl.glGetUniformLocation(self.shaders_program, "top")
gl.glUniform1f(top, self.top)
bottom = gl.glGetUniformLocation(self.shaders_program, "bottom")
gl.glUniform1f(bottom, self.bottom)
def paintGL(self):
self.resizeGL(self.width, self.height)
gl.glDisable(gl.GL_LINE_STIPPLE)
gl.glClearColor(1, 1,1, 0)
gl.glClear(gl.GL_COLOR_BUFFER_BIT)
self.vbo.bind()
gl.glEnableVertexAttribArray(0)
gl.glVertexAttribPointer(0, 2, gl.GL_FLOAT, gl.GL_FALSE, 0, None)
gl.glUseProgram(self.shaders_program)
self.ortho_view()
uni_color = gl.glGetUniformLocation(self.shaders_program, "triangleColor")
for i in range(0, self.vbo.data.shape[0]):
gl.glUniform3f(uni_color, 0, 0, 0)
# gl.glLineWidth(1.8)
gl.glDrawArrays(gl.GL_LINE_STRIP, i * self.count, self.count)
self.vbo.unbind()
def resizeGL(self, width, height):
self.width, self.height = width, height
gl.glViewport(0, 0, width, height)
def main():
app = QApplication(sys.argv)
editor = GLPlotWidget()
editor.show()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
Can anyone suggest me any method to solve this problem?
file link https://drive.google.com/file/d/1y6w35kuMguR1YczK7yMJpXU86T6qtGSv/view?usp=sharing
edit:- I tried to increase linewidth of points and set color to them but the result is not even close to satisfactory.. and I am unable to understand how to pass color in triangles?
Got it...I have rendered triangles and set color to get the desired result..
import OpenGL.GL as gl
import OpenGL.arrays.vbo as glvbo
from PyQt5.Qt import *
import numpy as np
import sys
import copy
VS = '''
#version 450
attribute vec2 position;
attribute vec3 a_Color;
out vec3 g_color;
void main() {
gl_Position = vec4(position.x, position.y, 0., 1.);
g_color = a_Color;
}
'''
FS = '''
#version 450
// Output variable of the fragment shader, which is a 4D vector containing the
// RGBA components of the pixel color.
in vec3 g_color;
out vec4 outColor;
void main()
{
outColor = vec4(g_color, 1.0);
}
'''
VS1 = '''
#version 450
layout(location = 0) in vec2 position;
void main() {
gl_Position = vec4(position.x, position.y, 0.0, 1.);
}
'''
FS1 = '''
#version 450
// Output variable of the fragment shader, which is a 4D vector containing the
// RGBA components of the pixel color.
uniform vec3 triangleColor;
out vec4 outColor;
void main()
{
outColor = vec4(triangleColor, 1.0);
}
'''
def compile_vertex_shader(source):
"""Compile a vertex shader from source."""
vertex_shader = gl.glCreateShader(gl.GL_VERTEX_SHADER)
gl.glShaderSource(vertex_shader, source)
gl.glCompileShader(vertex_shader)
# check compilation error
result = gl.glGetShaderiv(vertex_shader, gl.GL_COMPILE_STATUS)
if not (result):
raise RuntimeError(gl.glGetShaderInfoLog(vertex_shader))
return vertex_shader
def compile_fragment_shader(source):
"""Compile a fragment shader from source."""
fragment_shader = gl.glCreateShader(gl.GL_FRAGMENT_SHADER)
gl.glShaderSource(fragment_shader, source)
gl.glCompileShader(fragment_shader)
result = gl.glGetShaderiv(fragment_shader, gl.GL_COMPILE_STATUS)
if not (result):
raise RuntimeError(gl.glGetShaderInfoLog(fragment_shader))
return fragment_shader
def link_shader_program(vertex_shader, fragment_shader):
"""Create a shader program with from compiled shaders."""
program = gl.glCreateProgram()
gl.glAttachShader(program, vertex_shader)
gl.glAttachShader(program, fragment_shader)
gl.glLinkProgram(program)
result = gl.glGetProgramiv(program, gl.GL_LINK_STATUS)
if not (result):
raise RuntimeError(gl.glGetProgramInfoLog(program))
return program
class GLPlotWidget(QGLWidget):
def __init__(self, *args):
super(GLPlotWidget, self).__init__()
self.width, self.height = 100, 100
self.we = np.load('two.npy', mmap_mode='r')
self.e = copy.deepcopy(self.we[:, :, :])
self.e[:, :, 1] = np.interp(self.e[:, :, 1], (self.e[:, :, 1].min(), self.e[:, :, 1].max()),
(-1, 1))
self.e[:, :, 0] = np.interp(self.e[:, :, 0], (self.e[:, :, 0].min(), self.e[:, :, 0].max()),
(-1, +1))
self.vbo = glvbo.VBO(self.e)
self.count = self.vbo.shape[1]
self.showMaximized()
def initializeGL(self):
self.greyscale_data()
vs = compile_vertex_shader(VS1)
fs = compile_fragment_shader(FS1)
self.shaders_program_plot = link_shader_program(vs, fs)
def greyscale_data(self):
self.color = np.zeros((self.e.shape[1]*self.e.shape[0], 3), dtype=np.float32)
for i in range(0, 24):
a = self.e[i, :, 1].min()
b = self.e[i, :, 1].max()
c = np.interp(self.e[i, :, 1], (a, b), (0.15, 0.5))
self.color[self.e.shape[1] * i:self.e.shape[1] * (i + 1), 0] = c
self.color[self.e.shape[1] * i:self.e.shape[1] * (i + 1), 1] = c
self.color[self.e.shape[1] * i:self.e.shape[1] * (i + 1), 2] = c
self.elems = []
b = self.e.shape[1] # number of points per line
a = self.e.shape[0] # total number of arms
for i in range(0, a - 1):
for j in range(0, b - 1):
self.elems += [j + b * i, j + b * i + 1, j + b * (i + 1)]
self.elems += [j + b * (i + 1), j + b * (i + 1) + 1, j + b * i + 1]
self.elems = np.array(self.elems, dtype=np.int32)
# print(self.elems[0:100])
vs = compile_vertex_shader(VS)
fs = compile_fragment_shader(FS)
self.shaders_program = link_shader_program(vs, fs)
self.vertexbuffer = gl.glGenBuffers(1)
gl.glBindBuffer(gl.GL_ARRAY_BUFFER, self.vertexbuffer)
gl.glBufferData(gl.GL_ARRAY_BUFFER, self.e, gl.GL_DYNAMIC_DRAW)
self.elementbuffer = gl.glGenBuffers(1)
gl.glBindBuffer(gl.GL_ELEMENT_ARRAY_BUFFER, self.elementbuffer)
gl.glBufferData(gl.GL_ELEMENT_ARRAY_BUFFER, self.elems, gl.GL_DYNAMIC_DRAW)
self.colorbuffer = gl.glGenBuffers(1)
gl.glBindBuffer(gl.GL_ARRAY_BUFFER, self.colorbuffer)
gl.glBufferData(gl.GL_ARRAY_BUFFER, self.color, gl.GL_DYNAMIC_DRAW)
def ortho_view(self, i):
right = gl.glGetUniformLocation(i, "right")
gl.glUniform1f(right, self.right)
left = gl.glGetUniformLocation(i, "left")
gl.glUniform1f(left, self.left)
top = gl.glGetUniformLocation(i, "top")
gl.glUniform1f(top, self.top)
bottom = gl.glGetUniformLocation(i, "bottom")
gl.glUniform1f(bottom, self.bottom)
def greyscale(self):
gl.glUseProgram(self.shaders_program)
gl.glBindBuffer(gl.GL_ARRAY_BUFFER, self.vertexbuffer)
stride = 0 # 3*self.e.itemsize
offset = None # ctypes.c_void_p(0)
loc = gl.glGetAttribLocation(self.shaders_program, 'position')
gl.glEnableVertexAttribArray(loc)
gl.glVertexAttribPointer(loc, 2, gl.GL_FLOAT, False, stride, offset)
gl.glBindBuffer(gl.GL_ELEMENT_ARRAY_BUFFER, self.elementbuffer)
loc = gl.glGetAttribLocation(self.shaders_program, 'a_Color')
gl.glEnableVertexAttribArray(loc)
gl.glBindBuffer(gl.GL_ARRAY_BUFFER, self.colorbuffer)
gl.glVertexAttribPointer(loc, 3, gl.GL_FLOAT, False, stride, offset)
gl.glDrawElements(gl.GL_TRIANGLE_STRIP, self.elems.size, gl.GL_UNSIGNED_INT, None)
def paintGL(self):
self.resizeGL(self.width, self.height)
gl.glClearColor(1, 1, 1, 0)
gl.glClear(gl.GL_COLOR_BUFFER_BIT | gl.GL_DEPTH_BUFFER_BIT)
gl.glEnable(gl.GL_DEPTH_TEST)
self.vbo.bind()
gl.glEnableVertexAttribArray(0)
gl.glVertexAttribPointer(0, 2, gl.GL_FLOAT, gl.GL_FALSE, 0, None)
gl.glUseProgram(self.shaders_program_plot)
uni_color = gl.glGetUniformLocation(self.shaders_program_plot, "triangleColor")
for i in range(0, self.vbo.data.shape[0]):
gl.glUniform3f(uni_color, 0, 0, 0)
gl.glLineWidth(1)
gl.glDrawArrays(gl.GL_LINE_STRIP, i * self.count, self.count)
self.vbo.unbind()
self.greyscale()
gl.glUseProgram(0)
def resizeGL(self, width, height):
self.width, self.height = width, height
gl.glViewport(0, 0, width, height)
def main():
app = QApplication(sys.argv)
editor = GLPlotWidget()
editor.show()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
I'm creating this program to calculate the weight of animals in a camp, by getting the amount of animals of each age and then get the total amount of food they need daily.
I'm using Tkinter for the GUI where the amount of animals of each age is entered.
When i run the program the program doesn't retrieve the values that where entered and doesn't work with them?
I am completely new to Tkinter and fairly new to Python 3.6
I would be extremely grateful for any constructive criticism.
#Beginning
from tkinter import *
from math import *
import string
root = Tk()
#Function to calculate everything- Gets total weight of animals and then calculates feed
def enter_click(event):
global SabCow, SabBull, BuffBull, BuffCow, RoanCow, RoanBull, Six_Months,
One_Year, Two_Year, Three_Year, Big
M1_int = IntVar(M1.get())
M2_int = IntVar(M2.get())
M3_int = IntVar(M3.get())
M4_int = IntVar(M4.get())
M5_int = IntVar(M5.get())
F1_int = IntVar(F1.get())
F2_int = IntVar(F2.get())
F3_int = IntVar(F3.get())
F4_int = IntVar(F4.get())
F5_int = IntVar(F5.get())
#Work with which animal is selected form radiobutton, then calculate what is the weight of animals of each age then calculate food necessary
if A.get() == 1 :
f1_weight = F1_int * ((SabCow * 25)/Six_Months)
f2_weight = F2_int * ((SabCow * 40)/One_Year)
f3_weight = F3_int * ((SabCow * 70)/Two_Year)
f4_weight = F4_int * ((SabCow * 85)/Three_Year)
f5_weight = F5_int * SabCow
m1_weight = M1_int * ((SabBull * 25)/Six_Months)
m2_weight = M2_int * ((SabBull * 40)/One_Year)
m3_weight = M3_int * ((SabBull * 70)/Two_Year)
m4_weight = M4_int * ((SabBull * 85)/Three_Year)
m5_weight = M5_int * SabBull
Weight_Female = lambda f1_weight, f2_weight, f3_weight, f4_weight, f5_weight : f1_weight + f2_weight + f3_weight + f4_weight + f5_weight
Weight_Male = m1_weight + m2_weight + m3_weight + m4_weight + m5_weight
Total_Weight = Weight_Female + Weight_Male
Total_Food = Total_Weight * Big
animal = "Sable"
result_text = animal, "\nTotalFood Requierd: ", Total_Food, "\n", Total_Weight, "\n", Weight_Female, "\n", Weight_Male
return result_text
elif A.get() == 2 :
f1_weight = F1_int * ((BuffCow * 25)/Six_Months)
f2_weight = F2_int * ((BuffCow * 40)/One_Year)
f3_weight = F3_int * ((BuffCow * 70)/Two_Year)
f4_weight = F4_int * ((BuffCow * 85)/Three_Year)
f5_weight = F5_int * SabCow
m1_weight = M1_int * ((BuffBull * 25)/Six_Months)
m2_weight = M2_int * ((BuffBull * 40)/One_Year)
m3_weight = M3_int * ((BuffBull * 70)/Two_Year)
m4_weight = M4_int * ((BuffBull * 85)/Three_Year)
m5_weight = M5_int * BuffBull
Weight_Female = f1_weight + f2_weight + f3_weight + f4_weight + f5_weight
Weight_Male = m1_weight + m2_weight + m3_weight + m4_weight + m5_weight
Total_Weight = Weight_Female + Weight_Male
Total_Food = Total_Weight * Big
animal = "Buffalo"
result_text = animal, "\nTotalFood Requierd: ", Total_Food, "\n", Total_Weight, "\n", Weight_Female, "\n", Weight_Male
return result_text
elif A.get() == 3 :
f1_weight = F1_int * ((RoanCow * 25)/Six_Months)
f2_weight = F2_int * ((RoanCow * 40)/One_Year)
f3_weight = F3_int * ((RoanCow * 70)/Two_Year)
f4_weight = F4_int * ((RoanCow * 85)/Three_Year)
f5_weight = F5_int * RoanCow
m1_weight = M1_int * ((RoanBull * 25)/Six_Months)
m2_weight = M2_int * ((RoanBull * 40)/One_Year)
m3_weight = M3_int * ((RoanBull * 70)/Two_Year)
m4_weight = M4_int * ((RoanBull * 85)/Three_Year)
m5_weight = M5_int * RoanBull
Weight_Female = f1_weight + f2_weight + f3_weight + f4_weight + f5_weight
Weight_Male = m1_weight + m2_weight + m3_weight + m4_weight + m5_weight
Total_Weight = Weight_Female + Weight_Male
Total_Food = Total_Weight * Big
animal = "Roan"
result_text = animal, "\nTotalFood Requierd: ", Total_Food, "\n", Total_Weight, "\n", Weight_Female, "\n", Weight_Male
return result_text
print(result_text)
animal = StringVar()
#Animal Weight
BuffBull = 750
BuffCow = 650
SabBull = 230
SabCow = 210
RoanBull = 270
RoanCow = 240
#Animal Ages to Weight
Six_Months = 125
One_Year = 140
Two_Year = 170
Three_Year = 185
#Percentage Food needed of total KG
Big = 2/102
Small = 5/105
#Tkinter
A = IntVar()
A.set(1)
result_text = StringVar()
f1_weight = DoubleVar()
f2_weight = DoubleVar()
f3_weight = DoubleVar()
f4_weight = DoubleVar()
f5_weight = DoubleVar()
m1_weight = DoubleVar()
m2_weight = DoubleVar()
m3_weight = DoubleVar()
m4_weight = DoubleVar()
m5_weight = DoubleVar()
#GUI
w =Label(root, text="Choose an Animal:", justify=LEFT, padx=5,pady=10).grid(row=0)
o =Label(root, text="Results:", justify=LEFT, padx=5, pady=10).grid(row=7)
Label(root, text="Age", padx=5, pady=20).grid(row=0, column=2)
Label(root, text="M", padx=5, pady=20).grid(row=0, column=3)
Label(root, text="F", padx=5, pady=20).grid(row=0, column=4)
Radiobutton(root, text="Sable", padx=20, variable=A, value=1).grid(row=1)
Radiobutton(root, text="Buffalo", padx=20, variable=A, value=2).grid(row=2)
Radiobutton(root, text="Roan", padx=20, variable=A, value=3).grid(row=3)
Label(root, text="6 Months :").grid(row=1, column=2)
Label(root, text="1 Year :").grid(row=2, column=2)
Label(root, text="2 Years :").grid(row=3, column=2)
Label(root, text="3 Years :").grid(row=4, column=2)
Label(root, text="4 Years :").grid(row=5, column=2)
#Entry widgets-to get total of animals of each age
M1 = Entry(root)
M2 = Entry(root)
M3 = Entry(root)
M4 = Entry(root)
M5 = Entry(root)
F1 = Entry(root)
F2 = Entry(root)
F3 = Entry(root)
F4 = Entry(root)
F5 = Entry(root)
M1.grid(row=1, column=3)
M2.grid(row=2, column=3)
M3.grid(row=3, column=3)
M4.grid(row=4, column=3)
M5.grid(row=5, column=3)
F1.grid(row=1, column=4)
F2.grid(row=2, column=4)
F3.grid(row=3, column=4)
F4.grid(row=4, column=4)
F5.grid(row=5, column=4)
#Calculation button and event
enter_button=Button(root, text="Enter")
enter_button.grid(row=6)
enter_button.bind("<Enter>",enter_click)
enter_button.bind("<Return>",enter_click)
root.mainloop()
At this stage I've scouted the internet for 2 weeks with no help and now I also get this error when running the program:
AttributeError: 'str' object has no attribute '_root'
There is a multiple problems in your code.
First:
M1_int = IntVar(M1.get())
Should be like:
M1_int = float(M1.get())
(it is for all variables in M1...F7)
Second: in Weight_Female calculation you doesn't need lambda.
Third:A == 3 is always False. You need to get value form control like in first case (A.get() == 1).
I am pretty new to Python and are trying to make a option pricing class with three functions: call, put and graph. The call and put function work fine, but I can't figure out the graph function. I want the p.append to get the values from the call function, hold all the variables constant except for S0 which is equal to i.
import numpy as np
from scipy.stats import norm
import matplotlib.pyplot as plt
class Option():
def __init__(self, S0, K, T, r, sigma, start, stop, N):
self.S0 = S0
self.K = K
self.T = T
self.r = r
self.sigma = sigma
self.start = start
self.stop = stop
self.N = N
def call(self):
d1 = (np.log(self.S0/self.K) + \
(self.r + 0.5*self.sigma**2)*self.T)/(self.sigma*np.sqrt(self.T))
d2 = d1 - self.sigma*np.sqrt(self.T)
price = (self.S0 * norm.cdf(d1, 0.0, 1.0) - \
self.K * np.exp(-self.r * self.T) * norm.cdf(d2, 0.0, 1.0))
return price
def put(self):
d1 = (np.log(self.S0/self.K) + \
(self.r + 0.5*self.sigma**2)*self.T)/(self.sigma*np.sqrt(self.T))
d2 = d1 - self.sigma*np.sqrt(self.T)
price = (self.K * np.exp(-self.r * self.T) * norm.cdf(-d2, 0.0, 1.0) - \
self.S0 * norm.cdf(-d1, 0.0, 1.0))
return price
def graphCall(self):
S = np.linspace(self.start, self.stop, self.N)
p = []
for i in S:
p.append()
plt.plot(S, p)
x = Option(100, 50, 3, 0.05, 0.40, 100, 200, 500)
print(x.call())
x.graphCall()
You could decide to use self.S0 as the default value for calls to call and put, but allow for a other arguments as well.
import numpy as np
from scipy.stats import norm
import matplotlib.pyplot as plt
class Option():
def __init__(self, S0, K, T, r, sigma, start, stop, N):
self.S0 = S0
self.K = K
self.T = T
self.r = r
self.sigma = sigma
self.start = start
self.stop = stop
self.N = N
def call(self, s=None):
if s is None:
s=self.S0
d1 = (np.log(s/self.K) + \
(self.r + 0.5*self.sigma**2)*self.T)/(self.sigma*np.sqrt(self.T))
d2 = d1 - self.sigma*np.sqrt(self.T)
price = (s * norm.cdf(d1, 0.0, 1.0) - \
self.K * np.exp(-self.r * self.T) * norm.cdf(d2, 0.0, 1.0))
return price
def put(self, s=None):
if s is None:
s=self.S0
d1 = (np.log(s/self.K) + \
(self.r + 0.5*self.sigma**2)*self.T)/(self.sigma*np.sqrt(self.T))
d2 = d1 - self.sigma*np.sqrt(self.T)
price = (self.K * np.exp(-self.r * self.T) * norm.cdf(-d2, 0.0, 1.0) - \
s * norm.cdf(-d1, 0.0, 1.0))
return price
def graphCall(self):
S = np.linspace(self.start, self.stop, self.N)
plt.plot(S, self.call(S))
plt.show()
x = Option(100, 50, 3, 0.05, 0.40, 100, 200, 500)
print(x.call())
x.graphCall()
This is full code base. Im trying to simulate a mouse click in the graph which is self.graph which is a plotwidget. I want the mouse click to happen in the plotrunnable class so afte I click the graph button it will automatically update and right before going to sleep it will simulate a click on the graph to make it seem like its automatically updating
# Form implementation generated from reading ui file 'U:\Embedded Graphics View2.ui'
#
# Created by: PyQt5 UI code generator 5.9.2
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
import pyqtgraph as pg
import pyodbc as db
import pandas as pd
import time, os
from time import strptime as strptime
from time import mktime as mktime
from time import gmtime, strftime
from pyqtgraph import AxisItem
from datetime import datetime, timedelta
from numpy import ceil
import numpy as np
import sip
os.environ['TZ']='EST'
now=time.asctime(time.localtime())
start_time=time.time()
print('starting at '+now)
def time(date):
if date == '':
return None
else:
datetime = date
pattern = '%Y%m%d %H:%M:%S'
epoch = int(mktime(strptime(datetime, pattern)))
return epoch
def connecttosql():
host='{SQL Server}'
server='SERVER' ######### DEV - WILL CHANGE TO PRODUCTION WHEN DELIVERED
database='DB'
username='user'
password='pass'
try:
cs= 'Driver=%s;Server=%s;Uid=%s;Pwd=%s;Database=%s;' % (host,server, username, password, database)
global conn #### THIS WILL BE USED ON THE QUERY
conn= db.connect(cs)
print ('Connected successfully to '+host+', '+server)
except Exception as e:
print ('Error: ' + str (e))
def testconnection():
cursor=conn.cursor()
try:
cursor.execute("SELECT VERSION()")
res=cursor.fetchone()
print(res)
ver=res[0]
if ver in None:
return False
else:
return True
except:
print ("ERROR IN CONNECTION")
return False
def closeconnection():
conn.close
print('CONNECTION WITH DATABASE HAS BEEN CLOSED')
def query(ticker,interval,ST,ET):
# target='U:/py/sql csv/'+ticker+' - '+interval+'.csv'
global conn
table = 'BAR_BB' ### hard code
qry = f"SELECT * FROM {table} WHERE SY = {ticker} AND IL = {interval} AND ST >= {ST} AND ST <= {ET}"
df=pd.read_sql(qry,conn) ###### format will change
df.set_index('ST',inplace=True)
#df.to_csv(target,encoding='utf-8',index=False)
st=df.index.tolist()
op=df['O'].tolist()
hi=df['H'].tolist()
lo=df['L'].tolist()
cl=df['C'].tolist()
bars=[]
x=0
for i in st:
bar=[st[x],op[x],cl[x],lo[x],hi[x]]
bars.append(bar)
x=x+1
data=bars
return data
##Picture that goes in the UI
class CandlestickItem(pg.GraphicsObject):
def __init__(self):
pg.GraphicsObject.__init__(self)
self.flagHasData = False
#QtCore.pyqtSlot(list)
def set_data(self, data):
self.data = data
self.flagHasData = True
self.generatePicture()
self.informViewBoundsChanged()
def generatePicture(self):
## pre-computing a QPicture object allows paint() to run much more quickly,
## rather than re-drawing the shapes every time.
self.picture = QtGui.QPicture()
p = QtGui.QPainter(self.picture)
p.setPen(pg.mkPen('w'))
w = (self.data[1][0] - self.data[0][0]) / 3.
for (t, open, close, min, max) in self.data:
p.drawLine(QtCore.QPointF(t, min), QtCore.QPointF(t, max))
if open > close:
p.setBrush(pg.mkBrush('r'))
else:
p.setBrush(pg.mkBrush('g'))
p.drawRect(QtCore.QRectF(t-w, open, w*2, close-open))
p.end()
def paint(self, p, *args):
p.drawPicture(0, 0, self.picture)
def boundingRect(self):
## boundingRect _must_ indicate the entire area that will be drawn on
## or else we will get artifacts and possibly crashing.
## (in this case, QPicture does all the work of computing the bouning rect for us)
return QtCore.QRectF(self.picture.boundingRect())
class DateAxisItem(AxisItem):
"""
A tool that provides a date-time aware axis. It is implemented as an
AxisItem that interpretes positions as unix timestamps (i.e. seconds
since 1970).
The labels and the tick positions are dynamically adjusted depending
on the range.
It provides a :meth:`attachToPlotItem` method to add it to a given
PlotItem
"""
# Max width in pixels reserved for each label in axis
_pxLabelWidth = 80
def __init__(self, *args, **kwargs):
AxisItem.__init__(self, *args, **kwargs)
self._oldAxis = None
def tickValues(self, minVal, maxVal, size):
"""
Reimplemented from PlotItem to adjust to the range and to force
the ticks at "round" positions in the context of time units instead of
rounding in a decimal base
"""
maxMajSteps = int(size/self._pxLabelWidth)
dt1 = datetime.fromtimestamp(minVal)
dt2 = datetime.fromtimestamp(maxVal)
dx = maxVal - minVal
majticks = []
if dx > 63072001: # 3600s*24*(365+366) = 2 years (count leap year)
d = timedelta(days=366)
for y in range(dt1.year + 1, dt2.year):
dt = datetime(year=y, month=1, day=1)
majticks.append(mktime(dt.timetuple()))
elif dx > 5270400: # 3600s*24*61 = 61 days
d = timedelta(days=31)
dt = dt1.replace(day=1, hour=0, minute=0,
second=0, microsecond=0) + d
while dt < dt2:
# make sure that we are on day 1 (even if always sum 31 days)
dt = dt.replace(day=1)
majticks.append(mktime(dt.timetuple()))
dt += d
elif dx > 172800: # 3600s24*2 = 2 days
d = timedelta(days=1)
dt = dt1.replace(hour=0, minute=0, second=0, microsecond=0) + d
while dt < dt2:
majticks.append(mktime(dt.timetuple()))
dt += d
elif dx > 7200: # 3600s*2 = 2hours
d = timedelta(hours=1)
dt = dt1.replace(minute=0, second=0, microsecond=0) + d
while dt < dt2:
majticks.append(mktime(dt.timetuple()))
dt += d
elif dx > 1200: # 60s*20 = 20 minutes
d = timedelta(minutes=10)
dt = dt1.replace(minute=(dt1.minute // 10) * 10,
second=0, microsecond=0) + d
while dt < dt2:
majticks.append(mktime(dt.timetuple()))
dt += d
elif dx > 120: # 60s*2 = 2 minutes
d = timedelta(minutes=1)
dt = dt1.replace(second=0, microsecond=0) + d
while dt < dt2:
majticks.append(mktime(dt.timetuple()))
dt += d
elif dx > 20: # 20s
d = timedelta(seconds=10)
dt = dt1.replace(second=(dt1.second // 10) * 10, microsecond=0) + d
while dt < dt2:
majticks.append(mktime(dt.timetuple()))
dt += d
elif dx > 2: # 2s
d = timedelta(seconds=1)
majticks = range(int(minVal), int(maxVal))
else: # <2s , use standard implementation from parent
return AxisItem.tickValues(self, minVal, maxVal, size)
L = len(majticks)
if L > maxMajSteps:
majticks = majticks[::int(ceil(float(L) / maxMajSteps))]
return [(d.total_seconds(), majticks)]
def tickStrings(self, values, scale, spacing):
"""Reimplemented from PlotItem to adjust to the range"""
ret = []
if not values:
return []
if spacing >= 31622400: # 366 days
fmt = "%Y"
elif spacing >= 2678400: # 31 days
fmt = "%Y %b"
elif spacing >= 86400: # = 1 day
fmt = "%b/%d"
elif spacing >= 3600: # 1 h
fmt = "%b/%d-%Hh"
elif spacing >= 60: # 1 m
fmt = "%H:%M"
elif spacing >= 1: # 1s
fmt = "%H:%M:%S"
else:
# less than 2s (show microseconds)
# fmt = '%S.%f"'
fmt = '[+%fms]' # explicitly relative to last second
for x in values:
try:
t = datetime.fromtimestamp(x)
ret.append(t.strftime(fmt))
except ValueError: # Windows can't handle dates before 1970
ret.append('')
return ret
def attachToPlotItem(self, plotItem):
"""Add this axis to the given PlotItem
:param plotItem: (PlotItem)
"""
self.setParentItem(plotItem)
viewBox = plotItem.getViewBox()
self.linkToView(viewBox)
self._oldAxis = plotItem.axes[self.orientation]['item']
self._oldAxis.hide()
plotItem.axes[self.orientation]['item'] = self
pos = plotItem.axes[self.orientation]['pos']
plotItem.layout.addItem(self, *pos)
self.setZValue(-1000)
def detachFromPlotItem(self):
"""Remove this axis from its attached PlotItem
(not yet implemented)
"""
raise NotImplementedError() # TODO
class TimeAxisItem(pg.AxisItem):
def tickStrings(self, values, scale, spacing):
return [datetime.fromtimestamp(value) for value in values]
##UI SetUP
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(1442, 1018)
MainWindow.setAutoFillBackground(False)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.graphicsView = QtWidgets.QWidget(self.centralwidget)
self.flagHasData = False
self.graphicsView.setGeometry(QtCore.QRect(0, 0, 1201, 991))
font = QtGui.QFont()
font.setPointSize(18)
self.graphicsView.setFont(font)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
self.graphicsView.setObjectName("graphicsView")
self.lineEdit = QtWidgets.QLineEdit(self.centralwidget)
self.lineEdit.setEnabled(True)
self.lineEdit.setGeometry(QtCore.QRect(1280, 20, 151, 21))
font = QtGui.QFont()
font.setPointSize(11)
self.lineEdit.setFont(font)
self.lineEdit.setObjectName("lineEdit")
self.lineEdit_2 = QtWidgets.QLineEdit(self.centralwidget)
self.lineEdit_2.setGeometry(QtCore.QRect(1280, 80, 151, 20))
font = QtGui.QFont()
font.setPointSize(11)
self.lineEdit_2.setFont(font)
self.lineEdit_2.setText("")
self.lineEdit_2.setObjectName("lineEdit_2")
self.lineEdit_3 = QtWidgets.QLineEdit(self.centralwidget)
self.lineEdit_3.setGeometry(QtCore.QRect(1280, 160, 151, 20))
font = QtGui.QFont()
font.setPointSize(11)
self.lineEdit_3.setFont(font)
self.lineEdit_3.setObjectName("lineEdit_3")
self.lineEdit_4 = QtWidgets.QLineEdit(self.centralwidget)
self.lineEdit_4.setGeometry(QtCore.QRect(1280, 230, 151, 20))
font = QtGui.QFont()
font.setPointSize(11)
self.lineEdit_4.setFont(font)
self.lineEdit_4.setObjectName("lineEdit_4")
self.label = QtWidgets.QLabel(self.centralwidget)
self.label.setGeometry(QtCore.QRect(1280, 0, 91, 16))
self.label.setObjectName("label")
self.label_2 = QtWidgets.QLabel(self.centralwidget)
self.label_2.setGeometry(QtCore.QRect(1280, 60, 111, 16))
self.label_2.setObjectName("label_2")
self.label_3 = QtWidgets.QLabel(self.centralwidget)
self.label_3.setGeometry(QtCore.QRect(1280, 120, 51, 16))
self.label_3.setObjectName("label_3")
self.label_4 = QtWidgets.QLabel(self.centralwidget)
self.label_4.setGeometry(QtCore.QRect(1280, 190, 101, 16))
self.label_4.setObjectName("label_4")
self.pushButton = QtWidgets.QPushButton(self.centralwidget)
self.pushButton.setGeometry(QtCore.QRect(1280, 260, 75, 23))
self.pushButton.setObjectName("pushButton")
self.label_5 = QtWidgets.QLabel(self.centralwidget)
self.label_5.setGeometry(QtCore.QRect(1280, 140, 170, 20))
self.label_5.setObjectName("label_5")
self.label_6 = QtWidgets.QLabel(self.centralwidget)
self.label_6.setGeometry(QtCore.QRect(1280, 210, 170, 20))
self.label_6.setObjectName("label_6")
self.pushButton_2 = QtWidgets.QPushButton(self.centralwidget)
self.pushButton_2.setGeometry(QtCore.QRect(1360, 260, 75, 23))
self.pushButton_2.setObjectName("pushButton_2")
MainWindow.setCentralWidget(self.centralwidget)
self.statusbar = QtWidgets.QStatusBar(MainWindow)
self.statusbar.setObjectName("statusbar")
MainWindow.setStatusBar(self.statusbar)
self.pushButton.clicked.connect(self.btn_click)
self.pushButton_2.clicked.connect(self.clear)
self.main_layout = QtWidgets.QHBoxLayout()
self.graphicsView.setLayout(self.main_layout)
self.graph = None
self.glayout = None
self.data = []
self.vb = None
self.main_layout.addWidget(self.graph)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
##renaming all the Labels and Window
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "Graph Interface"))
self.label.setText(_translate("MainWindow", "Ticker (Bloomberg)"))
self.label_2.setText(_translate("MainWindow", "Interval (In Seconds)"))
self.label_3.setText(_translate("MainWindow", "Start Time"))
self.label_4.setText(_translate("MainWindow", "End Time (Optional)"))
self.pushButton.setText(_translate("MainWindow", "Graph"))
self.label_5.setText(_translate("MainWindow", "YYYYMMDD 00:00:00 (UTC)"))
self.label_6.setText(_translate("MainWindow", "YYYYMMDD 00:00:00 (UTC)"))
self.pushButton_2.setText(_translate("MainWindow", "Clear"))
global mouse_click_event
def mouse_click_event(self):
graph.clicked()
#Button Click function.
def btn_click(self):
global ticker, interval, start_time, end_time, graph
global DRAW_GRAPH
connecttosql()
self.data = [ ## fields are (time, open, close, min, max).
(1., 10, 13, 5, 15),
(2., 13, 17, 9, 20),
(3., 17, 14, 11, 23),
(4., 14, 15, 5, 19),
(5., 15, 9, 8, 22),
(6., 9, 15, 8, 16)]
self.graph = pg.PlotWidget(name = 'Whatever', aixsItems = {'bottom' : TimeAxisItem(orientation = 'bottom')})
# self.ticker = self.lineEdit.text()
#self.interval = self.lineEdit_2.text()
#self.start_time = time(self.lineEdit_3.text())
#self.end_time = time(self.lineEdit_4.text())
# if self.end_time == None:
# self.end_time = time(strftime("%Y%m%d %H:%M:%S", gmtime()))
# else:
# self.end_time = time((self.lineEdit_4.text()))
# self.ticker = "'{}'".format(self.ticker)
# self.interval = "'{}'".format(self.interval)
# ticker = self.ticker
# interval = self.interval
# start_time = self.start_time
# end_time = self.end_time
self.glayout = pg.GraphicsLayout()
self.vb = self.glayout.addViewBox()
self.vb.enableAutoRange(axis='xy',enable = True)
#self.data = query(self.ticker,self.interval,self.start_time,self.end_time)
self.item = CandlestickItem()
self.item.set_data(self.data)
self.graph.addItem(self.item)
self.axis1 = DateAxisItem(orientation = 'bottom')
self.axis1.attachToPlotItem(self.graph.getPlotItem())
self.graph.showGrid(y=True, alpha = 0.8)
self.main_layout.addWidget(self.graph)
runnable = PlotRunnable(self.item)
QtCore.QThreadPool.globalInstance().start(runnable)
def clear(self):
self.parent = self.graph.parent()
self.graph.setParent(None)
self.graph.setParent(self.parent)
class PlotRunnable(QtCore.QRunnable):
def __init__(self, it):
QtCore.QRunnable.__init__(self)
self.it = it
def run(self):
while True:
data = self.it.data
# end_time = end_time = time(strftime("%Y%m%d %H:%M:%S", gmtime()))
rand =[ ## fields are (time, open, close, min, max).
(1., 10, 13, 5, 15),
(2., 13, 17, 9, 20),
(3., 17, 14, 11, 23),
(4., 14, 15, 5, 19),
(5., 15, 9, 8, 22),
(6., 9, 15, 8, 16),
(7., 8, 16, 10, 17)]
new_bar = rand[-1]
data.append(new_bar)
QtCore.QMetaObject.invokeMethod(self.it, "set_data",
QtCore.Qt.QueuedConnection,
QtCore.Q_ARG(list, data))
#put mouse click here
print("ran")
#interval = int("{}".format(interval))
QtCore.QThread.msleep(1000)
import sys
app = QtWidgets.QApplication(sys.argv)
MainWindow = QtWidgets.QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
MainWindow.show()
if __name__ == '__main__':
import sys
if (sys.flags.interactive != 1) or not hasattr(QtCore, 'PYQT_VERSION'):
QtGui.QApplication.instance().exec_()