Moving Around A Python Canvas Without Using Scrollbars - python

Background:I have a program using Tkinter as the basis of the GUI. The program has a canvas which is populated with a large number of objects. Currently, in order to move all objects on the screen, I am simply binding a movement function to the tag 'all' which of course moves all objects on the screen. However, it is vital for me to keep track of all canvas object positions- i.e. after every move I log the new position, which seems unnecessarily complicated.
Question:
What is the best way to effectively scroll/drag around the whole canvas (several times the size of the screen) using only the mouse (not using scrollbars)?
My Attempts:I have implemented scrollbars and found several guides to setting up scrollbars, but none that deal with this particular requirement.
Example of disused scrollbar method:
from Tkinter import *
class Canvas_On:
def __init__(self, master):
self.master=master
self.master.title( "Example")
self.c=Canvas(self.master, width=find_res_width-20, height=find_res_height, bg='black', scrollregion=(0,0,5000,5000))
self.c.grid(row=0, rowspan=25, column=0)
self.c.tag_bind('bg', '<Control-Button-1>', self.click)
self.c.tag_bind('bg', '<Control-B1-Motion>', self.drag)
self.c.tag_bind('dot', '<Button-1>', self.click_item)
self.c.tag_bind('dot', '<B1-Motion>', self.drag_item)
draw=Drawing_Utility(self.c)
draw.drawer(self.c)
def click(self, event):
self.c.scan_mark(event.x, event.y)
def drag(self, event):
self.c.scan_dragto(event.x, event.y)
def click_item(self, event):
self.c.itemconfigure('dot 1 text', text=(event.x, event.y))
self.drag_item = self.c.find_closest(event.x, event.y)
self.drag_x, self.drag_y = event.x, event.y
self.c.tag_raise('dot')
self.c.tag_raise('dot 1 text')
def drag_item(self, event):
self.c.move(self.drag_item, event.x-self.drag_x, event.y-self.drag_y)
self.drag_x, self.drag_y = event.x, event.y
class Drawing_Utility:
def __init__(self, canvas):
self.canvas=canvas
self.canvas.focus_set()
def drawer(self, canvas):
self.canvas.create_rectangle(0, 0, 5000, 5000,
fill='black', tags='bg')
self.canvas.create_text(450,450, text='', fill='black', activefill='red', tags=('draggable', 'dot', 'dot 1 text'))
self.canvas.create_oval(400,400,500,500, fill='orange', activefill='red', tags=('draggable', 'dot', 'dot 2'))
self.canvas.tag_raise(("dot"))
root=Tk()
find_res_width=root.winfo_screenwidth()
find_res_height=root.winfo_screenheight()
run_it=Canvas_On(root)
root.mainloop()
My Particular Issue
My program generates all canvas object coordinates and then draws them. The objects are arranged in various patterns, but critically they must 'know' where each other is. When moving around the canvas using the method #abarnert kindly supplied, and a similar method I wrote that moved all canvas objects, the issue arises that each object 'thinks' it is at the canvas coordinates generated before the objects were drawn. For example if I drag the canvas 50 pixels to the left and clicked on an object in my program, it jumps 50 pixels back to the right to it's original position. My solution to this was to write some code that, upon release of the mouse button, logged the last position and updated the coordinate data of each object. However, I'm looking for a way to remove this last step- I was hoping there was a way to move the canvas such that the object positions were absolute, and assumed a function similar to a 'scroll' function would do this. I realise I've rambled here, but I've added a couple of lines to the example above which highlights my issue- by moving the canvas you can see that the coordinates change. Thank you again.

I'll give you the code for the simplest version first, then explain it so you can expand it as needed.
class Canvas_On:
def __init__(self, master):
# ... your original code here ...
self.c.bind('<Button-1>', self.click)
self.c.bind('<B1-Motion>', self.drag)
def click(self, event):
self.c.scan_mark(event.x, event.y)
def drag(self, event):
self.c.scan_dragto(event.x, event.y)
First, the easy part: scrolling the canvas manually. As the documentation explains, you use the xview and yview methods, exactly as your scrollbar commands do. Or you can just directly call xview_moveto and yview_moveto (or the foo_scroll methods, but they don't seem to be what you want here). You can see that I didn't actually use these; I'll explain below.
Next, to capture click-and-drag events on the canvas, you just bind <B1-Motion>, as you would for a normal drag-and-drop.
The tricky bit here is that the drag event gives you screen pixel coordinates, while the xview_moveto and yview_moveto methods take a fraction from 0.0 for the top/left to 1.0 for the bottom/right. So, you'll need to capture the coordinates of the original click (by binding <Button-1>; with that, the coordinates of the drag event, and the canvas's bbox, you can calculate the moveto fractions. If you're using the scale method and want to drag appropriately while zoomed in/out, you'll need to account for that as well.
But unless you want to do something unusual, the scan helper methods do exactly that calculation for you, so it's simpler to just call them.
Note that this will also capture click-and-drag events on the items on the canvas, not just the background. That's probably what you want, unless you were planning to make the items draggable within the canvas. In the latter case, add a background rectangle item (either transparent, or with whatever background you intended for the canvas itself) below all of your other items, and tag_bind that instead of binding the canvas itself. (IIRC, with older versions of Tk, you'll have to create a tag for the background item and tag_bind that… but if so, you presumably already had to do that to bind all your other items, so it's the same here. Anyway, I'll do that even though it shouldn't be necessary, because tags are a handy way to create groups of items that can all be bound together.)
So:
class Canvas_On:
def __init__(self, master):
# ... your original code here ...
self.c.tag_bind('bg', '<Button-1>', self.click)
self.c.tag_bind('bg', '<B1-Motion>', self.drag)
self.c.tag_bind('draggable', '<Button-1>', self.click_item)
self.c.tag_bind('draggable', '<B1-Motion>', self.drag_item)
# ... etc. ...
def click_item(self, event):
x, y = self.c.canvasx(event.x), self.c.canvasy(event.y)
self.drag_item = self.c.find_closest(x, y)
self.drag_x, self.drag_y = x, y
self.tag_raise(item)
def drag_item(self, event):
x, y = self.c.canvasx(event.x), self.c.canvasy(event.y)
self.c.move(self.drag_item, x-self.drag_x, y-self.drag_y)
self.drag_x, self.drag_y = x, y
class Drawing_Utility:
# ...
def drawer(self, canvas):
self.c.create_rectangle(0, 0, 5000, 5000,
fill='black', tags='bg')
self.c.create_oval(50,50,150,150, fill='orange', tags='draggable')
self.c.create_oval(1000,1000,1100,1100, fill='orange', tags='draggable')
Now you can drag the whole canvas around by its background, but dragging other items (the ones marked as 'draggable') will do whatever else you want instead.
If I understand your comments correctly, your remaining problem is that you're trying to use window coordinates when you want canvas coordinates. The section Coordinate Systems in the docs explains the distinction.
So, let's say you've got an item that you placed at 500, 500, and the origin is at 0, 0. Now, you scroll the canvas to 500, 0. The window coordinates of the item are now 0, 500, but its canvas coordinates are still 500, 500. As the docs say:
To convert from window coordinates to canvas coordinates, use the canvasx and canvasy methods

Related

How to delete a shape from canvas created by a function in tkinter python?

New to ktinker and I've met a problem that I can't find a solution to.
My goal is to animate a shape and allow it to move using a function inside a while loop, and the function generates the shape while the while loop deletes and refreshes the canvas.
My code look something like this:
def shape():
global a
a = screen.create_rectangle(x,100,x+50,200,fill = 'white')
while True:
shape(x,y)
x+=10
screen.update()
screen.delete(a)
time.sleep(0.03)
the code successfully creates a rectangle and it moves, but the code isn't deleting the rectangles. However, the code works fine and deletes the rectangles if I'm not using a function.
The proper way to animate objects on a tk.Canvas is different from pygame and other GUI frameworks.
tk.Canvas does not require a "blitting" process; the items do not need to be deleted, and recreated each frame.
The proper approach is to move existing items, either using the tk.Canvas.move method, or the tk.Canvas.coord method. The first moves the item by a provided δx and δy, whereas the second re-positions the item to the new coordinates passed to it.
Here is an example with tk.Canvas.move:
import tkinter as tk
def shape(x):
return screen.create_rectangle(x, 100, x+50 , 200, fill='white')
def animate(rect, dx=0, dy=0):
screen.move(rect, dx, dy)
screen.after(100, animate, rect, dx)
if __name__ == '__main__':
root = tk.Tk()
screen = tk.Canvas(root, width=400, height=400, bg='cyan')
screen.pack()
rect = shape(50)
animate(rect, dx=10)
root.mainloop()
Notice that we make use of the tk.mainloop provided by the framework, instead of a clumsy while True loop. The tk.after method is the correct approach to call a function (here animate) at regular intervals.
We also avoid the use of time.sleep which always results to problems and blocking the GUI.
Try updating the screen after you delete the shape.
def shape():
global a
a = screen.create_rectangle(x,100,x+50,200,fill = 'white')
while True:
shape(x,y)
x+=10
screen.update()
screen.delete(a)
screen.update()
time.sleep(0.03)

PyQT Painter drawing Polygons

In my QT application I'm drawing lots of polygons like this:
I'm animating these, so some polygons will receive a new color. This animation runs 4-5 times per second.
However, calling the paintEvent() of the Qt.Painter() 4-5 times/second redraws ALL polygons which results in performance issues. Its only updated once a second, which is too slow. As you may see in the picture below, only some polygons in the first 12 rows needs to be updated:
[![enter image description here][2]][2]
In the QT docs I have read that you can't really save the state of the things you've already drawn. So you have to redraw everything again. Am I missing something? Is there a trick to still achieve this?
This is what my paintEvent() basically looks like (simplified, reduced cyclomatic complexity)
for y in range(len(self.array)):
for x in range(len(self.array[0])):
if(this): # simplified to reduce cyclomatic complexity
painter.setBrush(QBrush(QColor(20, 0, 255)))
elif(that):
painter.setBrush(QBrush(QColor(175, 175, 175)))
else:
painter.setBrush(QBrush(QColor(0, 0, 0)))
hexa_size = self.array[y][x]
hexas = createHexagon(x, y, hexa_size) # external functions to calculate the hexagon size and position
painter.drawPolygon(hexas)
painter.end()
call (update on each Pin change):
while True:
while(stempel.readPin(0) == 0):
QApplication.processEvents()
time.sleep(0.01)
self.draw_area.update() # Pin state changed, update polygons
while(stempel.readPin(0) == 1):
QApplication.processEvents()
time.sleep(0.01)
Qt allows scheduling an update for only a portion (region) of the widget, thus optimizing the result. This requires two step:
calling update(QRect) with an appropriate rectangle that covers only the part of the widget that requires repainting;
checking the event.rect() and then implement painting in order to paint only that region;
If you know for sure that only the first X rows are going to change color, then:
self.draw_area.update(
QRect(0, 0, self.draw_area.width(), <height of the repainted rows>)
Then, in the paintEvent:
if event.rect().bottom() < <height of the repainted rows>:
rowRange = range(indexOfTheLastRowToRepaint + 1)
else:
rowRange = range(len(self.array))
Note that another solution could be using QPicture, which is a way to "serialize" a QPainter in order to improve performance and avoid unnecessary computations.
class DrawArea(QWidget):
cache = None
def paintEvent(self, event):
if not self.cache:
self.cache = QPicture()
cachePainter = QPainter(self.cache)
# draw on the painter
cachePainter.end()
painter = QPainter(self)
painter.drawPicture(0, 0, self.cache)
def resizeEvent(self, event):
self.cache = None
The code above is very minimalistic, you might create multiple QPictures for every group of row and then decide which one paint whenever you require it, even by combining the event.rect() checking as explained above.
The major benefit of this technique is that QPainter usually processes a QPicture pretty fast, so you don't have to do all computations required for rows, polygons, etc.
Finally, the image you provided seems very repetitive, almost like a texture. In that case, you might consider using a QPixmap for each group of rows and then create a QBrush with that QPixmap. In that case, you'll only need to call painter.fillRect(self.rect(), self.textureBrush).
Solved it myself by using a QGraphicsScene + QGraphicsView:
self.scene = QGraphicsScene()
self.graphicView = QGraphicsView(self.scene, self)
Creating a list where all polygons are being saved:
self.polygons = [ [0] * len(array[0]) for _ in range(len(array))]
Initial drawing of all polygons:
for y in range(len(array)):
for x in range(len(array[0])):
polygon_size = self.array[y][x]
polygon = createPoly(x, y, polygon_size)
self.polygons[y][x] = self.scene.addPolygon(polygon, QPen(Qt.NoPen), QBrush(Qt.black))
if(y % 50 == 0): QApplication.processEvents()
Update rows indivudually:
for poly_size in active_rows:
for active_row in active_rows[poly_size]:
for x in range(0, len(array[0])):
if(array[active_row][x] == int(poly_size)):
self.polygons[active_row][x].setBrush(QBrush(QColor(20, 0, 255)))
if(array[active_row - 2][x] > 0 and array[active_row - 2][x] == int(poly_size)):
self.polygons[active_row - 2][x].setBrush(QBrush(QColor(175, 175, 175)))

(Instantiating an array of Buttons, but only one works

I'm trying to create a GUI for a virtual board for the game Go. There should be an nxn grid of tiles where a player can place a stone, either black or white. Clicking on a tile will make it change from tan(the default) to black, click again to white, and click a third time to go back to tan. Player one can click once on a spot to place a stone there, and player two can click twice (you need to remove stones later, so three clicks resets it). I created a tile object and then used a nested for loop to instantiate 9 by 9 of them. Unfortunately, running the code only seems to produce 1 functional tile, not 81. This code should work on any python machine (I'm using Python 3.4), so you can try to run it and see for yourself. Can anyone point out the reason the loop is only running once?
from tkinter import *
window = Tk()
n = 9
"""
A tile is a point on a game board where black or white pieces can be placed. If there are no pieces, it remains tan.
The basic feature is the "core" field which is a tkinter button. when the color is changed, the button is configured to represent this.
"""
class tile(object):
core = Button(window, height = 2, width = 3, bg = "#F4C364")
def __init__(self):
pass
"""the cycle function makes the tile object actually change color, going between three options: black, white, or tan."""
def cycle(self):
color = self.core.cget("bg")
if(color == "#F4C364"): #tan, the inital value.
self.core.config(bg = "#111111")#white.
elif (color == "#111111"):
self.core.config(bg = "#DDDDDD")#black.
else:
self.core.config(bg = "#F4C364")#back to tan.
board = [] #create overall array
for x in range(n):
board.append([])#add subarrays inside it
for y in range(n):
board[x].append(tile())#add a tile n times in each of the n subarrays
T = board[x][y] #for clarity, T means tile
T.core.config(command = lambda: T.cycle()) #I do this now because cycle hadn't been defined yet when I created the "core" field
T.core.grid(row = x, column = y) #put them into tkinter.
window.mainloop()
As mhawke points out in his answer you need to make the core an instance variable, so that each Tile gets its own core.
And as I mention in my comment above, you also need to fix the Button's command callback function. The code you use in your question will call the .cycle() method of the current value of T, which happens to be the last tile created. So no matter where you click only the last tile changes color. One way to fix that is to pass the current tile as a default argument of the lambda function when you create it. But because you are using OOP to create your Tile there's a better way, which you can see below.
I've made a few modifications to your code.
Although many Tkinter examples use from tkinter import * it's not a good practice. When you do from some_module import * it brings all of the names from some_module into the current module (your script), which means you could accidentally override those names with your own names. Even worse, if you do import * with multiple modules each new module's names can clash with the previous module's names, and you have no way of knowing that's happened until you start getting mysterious bugs. Using import tkinter as tk means you need to do a little more typing, but it makes the resulting program less bug-prone and easier to read.
I've modified the __init__ method so that it is called with the window and the (x, y) location of the tile (it's customary to use x for the horizontal coordinate and y for the vertical coordinate). Each Tile object now keeps track of its current state, where 0=empty, 1=black, 2=white. This makes it easier to update the colors. And because we've passed in the window and (x, y) we can use that info to add the tile to the grid. The tile also remembers the location (in self.location), which may come in handy.
I've modified the cycle method so that it updates both the background color and the activebackground of the tile. So when the mouse hovers over the tile it changes to a color that's (roughly) halfway between its current color and the color it will turn if you click it. IMO, this is nicer than the tile always turning pale grey when the mouse hovers over it.
I've also optimized the code that creates all the tiles and stores them in the board list of lists.
import tkinter as tk
colors = (
#background, #activebackground
("#F4C364", "#826232"), #tan
("#111111", "#777777"), #black
("#DDDDDD", "#E8C8A8"), #white
)
class Tile(object):
""" A tile is a point on a game board where black or white pieces can be placed.
If there are no pieces, it remains tan.
The basic feature is the "core" field which is a tkinter button.
when the color is changed, the button is configured to represent this.
"""
def __init__(self, win, x, y):
#States: 0=empty, 1=black, 2=white
self.state = 0
bg, abg = colors[self.state]
self.core = tk.Button(win, height=2, width=3,
bg=bg, activebackground=abg,
command=self.cycle)
self.core.grid(row=y, column=x)
#self.location = x, y
def cycle(self):
""" the cycle function makes the tile object actually change color,
going between three options: black, white, or tan.
"""
#cycle to the next state. 0 -> 1 -> 2 -> 0
self.state = (self.state + 1) % 3
bg, abg = colors[self.state]
self.core.config(bg=bg, activebackground=abg)
#print(self.location)
window = tk.Tk()
n = 9
board = []
for y in range(n):
row = [Tile(window, x, y) for x in range(n)]
board.append(row)
window.mainloop()
The problem is that core is a class variable which is created once and shared by all instances of class tile. It should be an instance variable for each tile instance.
Move core = Button(window, height = 2, width = 3, bg = "#F4C364") into tile.__init__() like this:
class Tile(object):
def __init__(self):
self.core = Button(window, height = 2, width = 3, bg = "#F4C364")
The root of the problem is that core is shared by all instances of the class by virtue of how you've defined it. You need to move creation of the button into the initializer.
I also suggest moving the configuration of the command into the button itself. The caller shouldn't need (nor care) how the button works internally. Personally I'd have the tile inherit from Button, but if you favor composition over inheritance I'll stick with that.
Example:
class tile(object):
def __init__(self):
self.core = Button(window, height = 2, width = 3, bg = "#F4C364"
command=self.cycle)

Finding and Connecting Multiple Canvas Items in Python

Background: I have a code which generates the cartesian coordinates of a network of regular shapes (in this case triangles), and then plots the vertices of the shapes on a Tkinter Canvas as small circles. The process is automated and requires only height and width of the network to obtain a canvas output. Each vertex has the tags 'Vertex' and the vertex's number. Problem: I want to automatically connect the vertices of the shapes together (i.e dot to dot), I have looked into using find_closest and find_overlapping methods to do this, but as the network is composed of vertices at angles to one another, I often find find_overlapping to be unreliable (due to relying on a rectangular envelope), and find_closest appears limited to finding only one connection. As the vertices aren't necessarily connected in order, it is not possible to create a loop to simply connect vertex 1 --> vertex 2 etc. Question: Is there a way to efficiently get all of a vertex's neighbouring vertices and then 'connect the dots' without relying on individually creating lines between points using a manual method such as self.c.create_line(vertex_coord[1], vertex_coord[0], fill='black') for each connection? And would it be possible to share a small example of such a code? Thank you in advance for any help!Below is an abbreviated version of the canvas components of my code.Prototype Method:
from data_generator import *
run_coordinate_gen=data_generator.network_coordinates()
run_coordinate_gen.generator_go()
class Network_Canvas:
def __init__(self, canvas):
self.canvas=canvas
canvas.focus_set()
self.canvas.create_oval(Vertex_Position[0], dimensions[0], fill='black', tags=('Vertex1', Network_Tag, Vertex_Tag))
self.canvas.create_oval(Vertex_Position[5], dimensions[5], fill='black', tags=('Vertex2', Network_Tag, Vertex_Tag))
try:
self.canvas.create_line(Line_Position[5] ,Line_Position[0] , fill='black' tags=(Network_Tag,'Line1', Line_Tag )) #Connection Between 1 and 6 (6_1), Line 1
except:
pass
#Note: Line_Position, Dimensions and Vertex_Position are all lists composed of (x,y) cartesian coordinates in this case.
This is of course then replicated for each line and vertex throughout the network, but was only used for 90 vertices. The new version requires orders of magnitude more vertices and I am doing this with:
New Method:
#Import updated coordinate generator and run it as before
class Network_Canvas:
def __init__(self, canvas):
self.canvas=canvas
canvas.focus_set()
for V in range(len(vertex_coord_xy)):
self.canvas.create_text(vertex_coord_xy[V]+Text_Distance, text=V+1, fill='black', tags=(V, 'Text'), font=('Helvetica', '9'))
self.canvas.create_oval(vertex_coord_xy[V],vertex_coord_xy[V]+Diameter, fill='black', outline='black', tags=(V, 'Vertex'))
#loop to fit connections here (?)
I think any kind of nearest-neighbor search is going to be waay more time-intensive than just keeping track of the vertices, and there's no "automatic" connect-the-dots method that I can think of (plus, I don't see why such a method should be any faster than drawing them with create_line). Also, how will a nearest-neighbor search algorithm distinguish between the vertices of two separate, nearby (or overlapping) shapes if you aren't keeping track? Anyhow, in my opinion you've already got the right method; there are probably ways to optimize it.
I think that since your shapes are numerous, and there are complicated things you need to do with them, I would make a class for them, like the one I implemented below. It includes the "click to see neighboring vertices" functionality. All of the following code ran without errors. Image of the output shown below.
import Tkinter as TK
import tkMessageBox
# [Credit goes to #NadiaAlramli](http://stackoverflow.com/a/1625023/1460057) for the grouping code
def group(seq, groupSize):
return zip(*(iter(seq),) * groupSize)
Network_Tag, Vertex_Tag, Line_Tag = "network", "vertex", "line"
class Shape:
def __init__(self, canvas, vertexCoords, vertexDiam):
self.vertexIDs = []
self.perimeterID = None
self.vertexCoords = vertexCoords
self.vertexRadius = vertexDiam/2
self.canvas = canvas
def deleteVertices(self):
for ID in self.vertexIDs:
self.canvas.delete(ID)
self.vertexIDs = []
def bindClickToVertices(self):
coordsGrouped = group(self.vertexCoords, 2)
num = len(coordsGrouped)
for k in range(len(self.vertexIDs)):
others = [coordsGrouped[(k-1)%num], coordsGrouped[(k+1)%num]]
self.canvas.tag_bind(self.vertexIDs[k], '<Button-1>',
lambda *args:tkMessageBox.showinfo("Vertex Click", "Neighboring vertices: "+str(others)))
def drawVertices(self):
for x, y in group(self.vertexCoords, 2):
self.vertexIDs.append(self.canvas.create_oval(x-self.vertexRadius, y-self.vertexRadius, x+self.vertexRadius, y+self.vertexRadius, fill='black', tags=(Network_Tag, Vertex_Tag)))
self.bindClickToVertices()
def updateVertices(self):
self.deleteVertices()
self.drawVertices()
def deletePerimeter(self):
if self.perimeterID is not None:
self.canvas.delete(self.perimeterID)
self.perimeterID = None
def drawPerimeter(self):
print "creating line:", (self.vertexCoords + self.vertexCoords[0:2])
self.perimeterID = self.canvas.create_line(*(self.vertexCoords + self.vertexCoords[0:2]), fill='black', tags=(Network_Tag, Line_Tag))
def updatePerimeter(self):
self.deletePerimeter()
self.drawPerimeter()
def deleteShape(self):
self.deleteVertices()
self.deletePerimeter()
def updateShape(self):
self.updateVertices()
self.updatePerimeter()
It can be used very simply, like this:
root = TK.Tk()
frame = TK.Frame(root)
canvas = TK.Canvas(frame, width=1000, height=1000)
frame.grid()
canvas.grid()
# create a bunch of isoceles triangles in different places:
shapes = []
for dx, dy in zip(range(0,1000, 30), range(0,1000, 30)):
shapes.append(Shape(canvas, [0+dx, 0+dy, 10+dx, 10+dy, 20+dx, 0+dy], 5))
# draw (or redraw) the shapes:
for shape in shapes:
shape.updateShape()
# move one of the shapes and change it to a square
shapes[10].vertexCoords = [50, 10, 60, 10, 60, 20, 50, 20]
shapes[10].updateShape()
# delete all the odd-numbered shapes, just for fun:
for k in range(len(shapes)):
if k%2 == 1:
shape.deleteShape()
root.mainloop()
Output:

PySide Qt: Auto vertical growth for TextEdit Widget, and spacing between widgets in a vertical layout

I need to Solve two problems With my widget above.
I'd like to be able to define the amount of space put between the post widgets shown in the image (they look fine as is, but I wanna know it's done).
I'd like to grow the text edits vertically based on the amount of text they contain without growing horizontally.
For 1 the code that populates the widgets is as follows :
self._body_frame = QWidget()
self._body_frame.setMinimumWidth(750)
self._body_layout = QVBoxLayout()
self._body_layout.setSpacing(0)
self._post_widgets = []
for i in range(self._posts_per_page):
pw = PostWidget()
self._post_widgets.append(pw)
self._body_layout.addWidget(pw)
self._body_frame.setLayout(self._body_layout)
SetSpacing(0) doesn't bring things any closer, however SetSpacing(100) does increase it.
edit
(for Question 2) I haven't mentioned this, but I want the parent widget to have a vertical scrollbar.
I have answered my own question, but its wordy, and cause and affect based. A proper well written tutorial style answer to address both points gets the bounty :D
edit 2
Using my own answer below I have solved the problem. I'll be accepting my own answer now.
1) Layouts
The other answer on here is very unclear and possibly off about how layout margins work. Its actually very straightforward.
Layouts have content margins
Widgets have content margins
Both of these define a padding around what they contain. A margin setting of 2 on a layout means 2 pixels of padding on all sides. If you have parent-child widgets and layouts, which is always the case when you compose your UI, each object can specific margins which take effect individually. That is... a parent layout specifying a margin of 2, with a child layout specifying a margin of 2, will effectively have 4 pixels of margin being displayed (obviously with some frame drawing in between if the widget has a frame.
A simple layout example illustrates this:
w = QtGui.QWidget()
w.resize(600,400)
layout = QtGui.QVBoxLayout(w)
layout.setMargin(10)
frame = QtGui.QFrame()
frame.setFrameShape(frame.Box)
layout.addWidget(frame)
layout2 = QtGui.QVBoxLayout(frame)
layout2.setMargin(20)
frame2 = QtGui.QFrame()
frame2.setFrameShape(frame2.Box)
layout2.addWidget(frame2)
You can see that the top level margin is 10 on each side, and the child layout is 20 on each side. Nothing really complicated in terms of math.
Margin can also be specified on a per-side basis:
# left: 20, top: 0, right: 20, bottom: 0
layout.setContentsMargins(20,0,20,0)
There is also the option of setting spacing on a layout. Spacing is the pixel amount that is placed between each child of the layout. Setting it to 0 means they are right up against each other. Spacing is a feature of the layout, while margin is a feature of the entire object. A layout can have margin around it, and also spacing between its children. And, the children of the widget can have their own margins which are part of their individual displays.
layout.setSpacing(10) # 10 pixels between each layout item
2) Auto-Resizing QTextEdit
Now for the second part of your question. There are a few ways to create a auto-resizing QTextEdit I am sure. But one way to approach it is to watch for content changes in the document, and then adjust the widget based on the document height:
class Window(QtGui.QDialog):
def __init__(self):
super(Window, self).__init__()
self.resize(600,400)
self.mainLayout = QtGui.QVBoxLayout(self)
self.mainLayout.setMargin(10)
self.scroll = QtGui.QScrollArea()
self.scroll.setWidgetResizable(True)
self.scroll.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOn)
self.mainLayout.addWidget(self.scroll)
scrollContents = QtGui.QWidget()
self.scroll.setWidget(scrollContents)
self.textLayout = QtGui.QVBoxLayout(scrollContents)
self.textLayout.setMargin(10)
for _ in xrange(5):
text = GrowingTextEdit()
text.setMinimumHeight(50)
self.textLayout.addWidget(text)
class GrowingTextEdit(QtGui.QTextEdit):
def __init__(self, *args, **kwargs):
super(GrowingTextEdit, self).__init__(*args, **kwargs)
self.document().contentsChanged.connect(self.sizeChange)
self.heightMin = 0
self.heightMax = 65000
def sizeChange(self):
docHeight = self.document().size().height()
if self.heightMin <= docHeight <= self.heightMax:
self.setMinimumHeight(docHeight)
I subclassed QTextEdit -> GrowingTextEdit, and connected the signal emitted from its document to a slot sizeChange that checks the document height. I also included a heightMin and heightMax attribute to let you specify how large or small its allowed to autogrow. If you try this out, you will see that as you type into the box, the widget will start to resize itself, and also shrink back when you remove lines. You can also turn off the scrollbars if you want. Right now each text edit has its own bars, in addition to the parent scroll area. Also, I think you could add a small pad value to the docHeight so that it expands just enough to not show scrollbars for the content.
This approach is not really low level. It uses the commonly exposed signals and child members of the widget for you to receive notifications of state changes. Its pretty common to make use of the signals for extending functionality of existing widgets.
To Address Question 1:
Parent Widgets and Layouts both have margins, in addition to the spacing parameter of the layout itself. From some cause and affect testing It is apprent that margins apply both to the outer region of a parent as well as an internal region.
So, for example if a 2 pixel margin is specified to a parent the vertical border has <--2 pixel | 2 pixel --> margin in addition to the margins of the layout (A HBoxLayout in this case). If the layout has a 2 pixel margin as well the area around horizontal line would look like:
<-- 2 pixel | 2 pixel --> <-- 2 pixel (L) 2 pixel--> (W)
edit Perhaps its more like this: | 2 pixel --> (L) 2 pixel --> <-- 2 pixel (W)
Where | is the vertical line of the parent (L) is the vertical line of the Layout and (W) is the border of the embedded widget in the horizontal layout.
The spacing of the layout is an additional parameter that controls how much space is inserted between widgets of the layout in addition to any layout margins.
The description above might not be accurate( so feel free to edit it where it is inaccurate), but setting the margins of the parent and the layout to zero as well as the layouts spacing to zero produces the result you are after.
For point 2:
I do not think there is a straight forward way to address this issue (you probably have to resort to hooking in at a lower level, which requires a deeper understanding of the API). I think you should use the QLabel Widget instead of the QTextEdit widget. Labels do not have a view and thus expand as needed, at least thats how they work by default, as long as the parent isn't constrained in it's movement.
So, change the QTextEdit to Qlabel and add a scrolling view to the parent and everything should work as you want. I have a feeling you chose QTextEdit because of it's background. Research the way HTML works in QT widgets and you might be able to alter the background via HTML.
edit
This widget (excuse the size) is created by the following code on OS X with PyQT:
import sys
from PyQt4 import Qt
class PostMeta(Qt.QWidget):
posted_at_base_text = "<b> Posted At:</b>"
posted_by_base_text = "<b> Posted By:</b>"
def __init__(self):
Qt.QWidget.__init__(self)
self._posted_by_label = Qt.QLabel()
self._posted_at_label = Qt.QLabel()
layout = Qt.QVBoxLayout()
layout.setMargin(0)
layout.setSpacing(5)
layout.addWidget(self._posted_by_label)
layout.addWidget(self._posted_at_label)
layout.addStretch()
self.setLayout(layout)
self._posted_by_label.setText(PostMeta.posted_by_base_text)
self._posted_at_label.setText(PostMeta.posted_at_base_text)
class FramePost(Qt.QFrame):
def __init__(self):
Qt.QFrame.__init__(self)
layout = Qt.QHBoxLayout()
layout.setMargin(10)
self.te = Qt.QLabel()
self.te.setStyleSheet("QLabel { background : rgb(245,245,245) }")
self.te.setFrameStyle( Qt.QFrame.Panel | Qt.QFrame.Sunken)
self.te.setLineWidth(1)
self._post_meta = PostMeta()
layout.addWidget(self._post_meta)
vline = Qt.QFrame()
vline.setFrameShape(Qt.QFrame.VLine)
layout.addWidget(vline)
layout.addWidget(self.te)
self.te.setText(
""" line one
line two
line three
line four
line five
line six
line seven
line eight
line nine
line ten
line eleven
line twelve
line thirteen""")
self.setLayout(layout)
self.setFrameStyle(Qt.QFrame.Box)
self.setLineWidth(2)
app = Qt.QApplication(sys.argv)
w = Qt.QWidget()
layout = Qt.QHBoxLayout()
fp = FramePost()
layout.addWidget(fp)
w.setLayout(layout)
w.show()
app.exec_()
The labels in the left widget show the spacer and margin tweaking done, and I've used a QLabel for the post text. Notice I've tweaked the label to look a bit more like a default QTextEdit

Categories

Resources