Strech image to window size in pyqtgraph - qt

I'm currently trying to create a PyQtGraph gui to plot an image repeatedly as new data comes in using code similar to this:
self.app = QtGui.QApplication([])
self.win = QtGui.QMainWindow()
self.win.resize(800, 600)
self.imv = pg.ImageView()
self.win.setCentralWidget(self.imv)
self.win.setWindowTitle('My Title')
self.timer = QtCore.QTimer()
self.timer.timeout.connect(self.check_for_new_data_and_replot)
self.timer.start(100)
self.win.show()
then each time I get new data I draw the image:
self.imv.setImage(self.data_array)
One problem I'm running into is that my data array usually has a skewed aspect ratio, i.e. it is usually really "tall and skinny" or "short and fat", and the image that is plotted has the same proportions.
Is there a way to stretch the image to fit the window? I've looked through the documentation for ImageView and ImageItem, but can't find what I need. (Perhaps it is there, but I am having trouble identifying it.)

I figured it out-- using the lower-level ImageItem class displayed the image in a way that stretched to fit the window size:
self.app = QtGui.QApplication([])
self.win = pg.GraphicsLayoutWidget()
self.win.resize(800, 600)
self.img = pg.ImageItem()
self.plot = self.win.addPlot()
self.plot.addItem(self.img)
self.win.setWindowTitle('My Title')
self.timer = QtCore.QTimer()
self.timer.timeout.connect(self.check_for_new_data_and_replot)
self.timer.start(100)
self.win.show()
And to update the image data:
self.img.setImage(self.data_array)
This also lets me display axis scales on the sides, which was a feature I wanted as well.

Related

Should I use QGraphicsView to display an image and some decorated text side by side?

I want to create a "details" view for books I have downloaded.
With the attached image as an example, imagine the red block to the left is the book's cover page, and metadata related to it is displayed to the right.
With the way I have it done right now:
from PySide6 import QtWidgets as qtw
from PySide6 import QtGui as qtg
from PySide6 import QtCore as qtc
class Details:
def __init__(self):
self.location = "/home/user/Desktop/Untitled.png"
self.title = "Some title"
self.subtitle = "Sub title"
self.id = 123124
def to_html(self):
return """
<p>
<b>Author =</b> author<br/>
<b>Published Date =</b> 2000-1-1<br/>
<b>Pages =</b> 500<br/>
</p>
"""
class DetailsWidget(qtw.QWidget):
_title_font = qtg.QFont()
_title_font.setBold(True)
_title_font.setPixelSize(24)
_subtitle_font = qtg.QFont()
_subtitle_font.setBold(True)
_subtitle_font.setPixelSize(19)
_id_font = qtg.QFont()
_id_font.setBold(True)
_id_font.setPixelSize(15)
_redacted_details_font = qtg.QFont()
_redacted_details_font.setPixelSize(12)
def __init__(self, *args, **kwargs) -> None:
super().__init__(*args, **kwargs)
self.setFixedSize(1000, 500)
self.setWindowFlag(qtc.Qt.WindowType.Dialog, True)
self.setLayout(qtw.QGridLayout())
self.layout().setContentsMargins(0, 0, 0, 0)
self._details: Details = Details()
self._thumbnail_image = qtg.QImage(self._details.location)
self._thumbnail_image = self._thumbnail_image.scaled(
500,
500,
qtc.Qt.AspectRatioMode.KeepAspectRatio,
qtc.Qt.TransformationMode.SmoothTransformation,
)
self._details_rect = qtc.QRect(
self._get_actual_geometry().left() + self._thumbnail_image.width() + 10,
self._get_actual_geometry().top(),
self._get_actual_geometry().width() - self._thumbnail_image.width() - 20,
self._get_actual_geometry().height(),
)
height = 0
self._title_rects = []
font_metrics_rect = qtg.QFontMetrics(self._title_font).boundingRect(
self._details_rect, qtc.Qt.TextFlag.TextWordWrap, self._details.title, 0
)
drawing_rect = qtc.QRect(self._details_rect)
self._title_rects.append(drawing_rect)
height += font_metrics_rect.height() + 10
drawing_rect = qtc.QRect(self._details_rect)
drawing_rect.moveTop(height)
self._title_rects.append(drawing_rect)
font_metrics_rect = qtg.QFontMetrics(self._title_font).boundingRect(
self._details_rect, qtc.Qt.TextFlag.TextWordWrap, self._details.subtitle, 0
)
drawing_rect = qtc.QRect(self._details_rect)
height += font_metrics_rect.height() - 3
drawing_rect.moveTop(height)
self._title_rects.append(drawing_rect)
font_metrics_rect = qtg.QFontMetrics(self._title_font).boundingRect(
self._details_rect,
qtc.Qt.TextFlag.TextWordWrap,
str(self._details.id),
0,
)
self._title_rects.append(drawing_rect)
height += font_metrics_rect.height() + 10
self._details_rect.moveTop(height)
self._redacted_details_text_document = qtg.QTextDocument()
self._redacted_details_text_document.setHtml(self._details.to_html())
# First set the width,
self._redacted_details_text_document.setTextWidth(self._details_rect.width())
# then get the height of the QTextDocument based on the given width and set
# that + the titles heights + bottom padding as the total height.
if (total_height:=height + self._redacted_details_text_document.size().height() + 10) > self.height():
self.setFixedHeight(total_height)
def _get_actual_geometry(self) -> qtc.QRect:
# Probably not needed for normal desktop environments with window
# managers but I'm an epik i3 user so self.geometry() does not work as
# intended when full screening the window with $mod + F. Or I'm just
# retarded and this is not even a problem.
geometry = self.geometry()
geometry.setTopLeft(qtc.QPoint(0, 0))
return geometry
def paintEvent(self, event: qtg.QPaintEvent) -> None:
total_height = 0
painter = qtg.QPainter(self)
painter.setRenderHint(qtg.QPainter.RenderHint.TextAntialiasing)
painter.drawImage(0, 0, self._thumbnail_image)
painter.save()
painter.setFont(self._title_font)
painter.drawText(
self._title_rects[0], qtc.Qt.TextFlag.TextWordWrap, self._details.title
)
painter.setFont(self._subtitle_font)
painter.drawText(
self._title_rects[1], qtc.Qt.TextFlag.TextWordWrap, self._details.subtitle
)
painter.setFont(self._id_font)
painter.drawText(
self._title_rects[2],
qtc.Qt.TextFlag.TextWordWrap,
str(self._details.id),
)
painter.translate(self._details_rect.topLeft())
painter.setFont(self._redacted_details_font)
self._redacted_details_text_document.drawContents(painter)
painter.restore()
app = qtw.QApplication()
widget = DetailsWidget()
widget.show()
app.exec()
I can display the text and the image next to each other just fine, but the text is not selectable. Looking around for a way to do so, I stumbled upon QGraphicsTextItem. Should I re-do the whole thing in a QGraphicsView instead of using the paintEvent on a QWidget? The reason I'm hesitant to do so is because I don't know of the cons of using a QGraphicsView, maybe it's a lot more resource heavy and not the best for this use case?
You're complicating things unnecessarily.
Just use a basic QHBoxLayout and two QLabels, with the one on the left for the image, and the one on the right for the details.
If you want to allow text selection, use QLabel.setTextInteractionFlags(Qt.TextSelectableByMouse).
An even better solution would be to use a QGraphicsView with a QGraphicsPixmapItem for the image (using fitInView() in the resizeEvent to always show it as large as possible) and a QTextEdit for the details, set in read only mode.
Note that your usage of _get_actual_geometry is wrong in principle (besides the fact that you're calling 4 times in a row, while you could just use a local variable instead), because when a widget has not been shown yet it always has a default size (100x30 for widgets created with a parent, otherwise 640x480), so not only you'll be getting a wrong geometry, but you're also changing it, since setTopLeft() will only move the corner, not translate the rectangle: if you want the basic rectangle of the widget, just use rect(). Obviously, if you properly use layouts as suggested above, this won't be necessary in the first place.

Altering code to place 2D UIImage as opposed to 3D shape geometry

I've been following a tutorial to create an AR Ruler. Therefore, with the code below, I'm able to place 3D sphere's in my scene (which im looking to keep for the tracking functionality). However, instead of a 3d image, I'm looking to place an image. I attempted changing the dotGeometry and setting it to a UIImage and commenting out the material code but wasn't sure how to deal with with dotNode piece of code. Therefore, how would I be able to set my image as the resulting on-screen addition?
let dotGeometry = SCNSphere(radius: 0.005)
let material = SCNMaterial()
material.diffuse.contents = UIColor.red
dotGeometry.materials = [material]
let dotNode = SCNNode(geometry: dotGeometry)
dotNode.position = SCNVector3(hitResult.worldTransform.columns.3.x, hitResult.worldTransform.columns.3.y, hitResult.worldTransform.columns.3.z)
sceneView.scene.rootNode.addChildNode(dotNode)
You could create a SCNBox and set its length to a very small value to make it appear flat.
let box = SCNBox(width: 0.2, height: 0.2, length: 0.005, chamferRadius: 0)
let material = SCNMaterial()
material.diffuse.contents = UIImage(named: "image.png")
box.materials = [material]
boxNode = SCNNode(geometry: box)
boxNode.opacity = 1.0
boxNode.position = SCNVector3(0,0,-0.5)
scene.rootNode.addChildNode(boxNode)
Or you could follow another approach and add an overlay SKScene (2D) to the SCNScene(3D) as described here : How can I overlay a SKScene over a SCNScene in Swift?

Displaying image on point hover in Plotly

Plotly allows you to display text fields when hovering over a point on a scatterplot. Is it possible to instead display an image associated with each point when the user hovers over or clicks on it? I am mostly just using the web interface, but I could instead push my ggplot from R.
Unfortunately, there is no easy way to display images on hover on plotly graphs at the moment.
If you are willing to learn some javascript, plotly's embed API allows you to customize hover (as well as click) interactivity.
Here is an example of a custom hover interaction showing images on top of a plotly graph. The javascript source code can be found here.
Images on hover is now available by Plotly lib. Here is a sample:
from dash import Dash, dcc, html, Input, Output, no_update
import plotly.graph_objects as go
import pandas as pd
# Small molcule drugbank dataset
# Source: https://raw.githubusercontent.com/plotly/dash-sample-apps/main/apps/dash-drug-discovery/data/small_molecule_drugbank.csv'
data_path = 'datasets/small_molecule_drugbank.csv'
df = pd.read_csv(data_path, header=0, index_col=0)
fig = go.Figure(data=[
go.Scatter(
x=df["LOGP"],
y=df["PKA"],
mode="markers",
marker=dict(
colorscale='viridis',
color=df["MW"],
size=df["MW"],
colorbar={"title": "Molecular<br>Weight"},
line={"color": "#444"},
reversescale=True,
sizeref=45,
sizemode="diameter",
opacity=0.8,
)
)
])
# turn off native plotly.js hover effects - make sure to use
# hoverinfo="none" rather than "skip" which also halts events.
fig.update_traces(hoverinfo="none", hovertemplate=None)
fig.update_layout(
xaxis=dict(title='Log P'),
yaxis=dict(title='pkA'),
plot_bgcolor='rgba(255,255,255,0.1)'
)
app = Dash(__name__)
app.layout = html.Div([
dcc.Graph(id="graph-basic-2", figure=fig, clear_on_unhover=True),
dcc.Tooltip(id="graph-tooltip"),
])
#app.callback(
Output("graph-tooltip", "show"),
Output("graph-tooltip", "bbox"),
Output("graph-tooltip", "children"),
Input("graph-basic-2", "hoverData"),
)
def display_hover(hoverData):
if hoverData is None:
return False, no_update, no_update
# demo only shows the first point, but other points may also be available
pt = hoverData["points"][0]
bbox = pt["bbox"]
num = pt["pointNumber"]
df_row = df.iloc[num]
img_src = df_row['IMG_URL']
name = df_row['NAME']
form = df_row['FORM']
desc = df_row['DESC']
if len(desc) > 300:
desc = desc[:100] + '...'
children = [
html.Div([
html.Img(src=img_src, style={"width": "100%"}),
html.H2(f"{name}", style={"color": "darkblue"}),
html.P(f"{form}"),
html.P(f"{desc}"),
], style={'width': '200px', 'white-space': 'normal'})
]
return True, bbox, children
if __name__ == "__main__":
app.run_server(debug=True)
More info: https://dash.plotly.com/dash-core-components/tooltip

In QDialog, resize window to contain all columns of QTableView

I am writing a simple program to display the contents of a SQL database table in a QDialog (PySide). The goal is to have a method that expands the window to show all of the columns, so the user doesn't have to resize to see everything. This problem was addressed in a slightly different context:
Fit width of TableView to width of content
Based on that, I wrote the following method:
def resizeWindowToColumns(self):
frameWidth = self.view.frameWidth() * 2
vertHeaderWidth = self.view.verticalHeader().width()
horizHeaderWidth =self.view.horizontalHeader().length()
vertScrollWidth = self.view.style().pixelMetric(QtGui.QStyle.PM_ScrollBarExtent)
fudgeFactor = 6 #not sure why this is needed
newWidth = frameWidth + vertHeaderWidth + horizHeaderWidth + vertScrollWidth + fudgeFactor
It works great. But notice that I have had to add a fudgeFactor. With fudge, it works perfectly. But it suggests I have lost track of six pixels, and am very curious where they are coming from. It doesn't seem to matter how many columns are displayed, or their individual widths: the fudgeFactor 6 always seems to work.
System details
Python 2.7 (Spyder/Anaconda). PySide version 1.2.2, Qt version 4.8.5. Windows 7 laptop with a touch screen (touch screens sometimes screw things up in PySide).
Full working example
# -*- coding: utf-8 -*-
import os
import sys
from PySide import QtGui, QtCore, QtSql
class DatabaseInspector(QtGui.QDialog):
def __init__(self, tableName, parent = None):
QtGui.QDialog.__init__(self, parent)
#define model
self.model = QtSql.QSqlTableModel(self)
self.model.setTable(tableName)
self.model.select()
#View of model
self.view = QtGui.QTableView()
self.view.setModel(self.model)
#Sizing
self.view.resizeColumnsToContents() #Resize columns to fit content
self.resizeWindowToColumns() #resize window to fit columns
#Quit button
self.quitButton = QtGui.QPushButton("Quit");
self.quitButton.clicked.connect(self.reject)
#Layout
layout = QtGui.QVBoxLayout()
layout.addWidget(self.view) #table view
layout.addWidget(self.quitButton) #pushbutton
self.setLayout(layout)
self.show()
def resizeEvent(self, event):
#This is just to see what's going on
print "Size set to ({0}, {1})".format(event.size().width(), event.size().height())
def resizeWindowToColumns(self):
#Based on: https://stackoverflow.com/a/20807145/1886357
frameWidth = self.view.frameWidth() * 2
vertHeaderWidth = self.view.verticalHeader().width()
horizHeaderWidth =self.view.horizontalHeader().length()
vertScrollWidth = self.view.style().pixelMetric(QtGui.QStyle.PM_ScrollBarExtent)
fudgeFactor = 6 #not sure why this is needed
newWidth = frameWidth + vertHeaderWidth + horizHeaderWidth + vertScrollWidth + fudgeFactor
if newWidth <= 500:
self.resize(newWidth, self.height())
else:
self.resize(500, self.height())
def populateDatabase():
print "Populating table in database..."
query = QtSql.QSqlQuery()
if not query.exec_("""CREATE TABLE favorites (
id INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE NOT NULL,
category VARCHAR(40) NOT NULL,
number INTEGER NOT NULL,
shortdesc VARCHAR(20) NOT NULL,
longdesc VARCHAR(80))"""):
print "Failed to create table"
return False
categories = ("Apples", "Chocolate chip cookies", "Favra beans")
numbers = (1, 2, 3)
shortDescs = ("Crispy", "Yummy", "Clarice?")
longDescs = ("Healthy and tasty", "Never not good...", "Awkward beans for you!")
query.prepare("""INSERT INTO favorites (category, number, shortdesc, longdesc)
VALUES (:category, :number, :shortdesc, :longdesc)""")
for category, number, shortDesc, longDesc in zip(categories, numbers, shortDescs, longDescs):
query.bindValue(":category", category)
query.bindValue(":number", number)
query.bindValue(":shortdesc", shortDesc)
query.bindValue(":longdesc", longDesc)
if not query.exec_():
print "Failed to populate table"
return False
return True
def main():
import site
app = QtGui.QApplication(sys.argv)
#Connect to/initialize database
dbName = "food.db"
tableName = "favorites"
site_pack_path = site.getsitepackages()[1]
QtGui.QApplication.addLibraryPath('{0}\\PySide\\plugins'.format(site_pack_path))
db = QtSql.QSqlDatabase.addDatabase("QSQLITE")
fullFilePath = os.path.join(os.path.dirname(__file__), dbName) #;print fullFilePath
dbExists = QtCore.QFile.exists(fullFilePath) #does it already exist in directory?
db.setDatabaseName(fullFilePath)
db.open()
if not dbExists:
populateDatabase()
#Display database
dataTable = DatabaseInspector(tableName)
sys.exit(app.exec_())
#Close and delete database (not sure this is needed)
db.close()
del db
if __name__ == "__main__":
main()
The difference between the linked question and your example, is that the former is resizing a widget within a layout, whereas the latter is resizing a top-level window.
A top-level window is usually decorated with a frame. On your system, the width of this frame seems to be three pixels on each side, making six pixels in all.
You can calculate this value programmatically with:
self.frameSize().width() - self.width()
where self is the top-level window.
However, there may be an extra issue to deal with, and that is in choosing when to calculate this value. On my Linux system, the frame doesn't get drawn until the window is fully shown - so calculating during __init__ doesn't work.
I worked around that problem like this:
dataTable = DatabaseInspector(tableName)
dataTable.show()
QtCore.QTimer.singleShot(10, dataTable.resizeWindowToColumns)
but I'm not sure whether that's portable (or even necessarily the best way to do it).
PS:
It seems that the latter issue may be specific to X11 - see the Window Geometry section in the Qt docs.
UPDATE:
The above explanation and calculation is not correct!
The window decoration is only relevant when postioning windows. The resize() and setGeometry() functions always exclude the window frame, so it doesn't need to be factored in when calculating the total width.
The difference between resizing a widget within a layout versus resizing a top-level window, is that the latter needs to take account of the layout margin.
So the correct calculation is this:
margins = self.layout().contentsMargins()
self.resize((
margins.left() + margins.right() +
self.view.frameWidth() * 2 +
self.view.verticalHeader().width() +
self.view.horizontalHeader().length() +
self.view.style().pixelMetric(QtGui.QStyle.PM_ScrollBarExtent)
), self.height())
But note that this always allows room for a vertical scrollbar.
The example script doesn't add enough rows to show the vertical scrollbar, so it is misleading in that respect - if more rows are added, the total width is exactly right.

QTextEdit is too big?

I can't figure out why my QTextEdit is so big despite my having inserted it without stretch. I just want it to be one line.
self.widget = QWidget()
vbox = QVBoxLayout()
vbox.addWidget(self.ppd_widget, 1) # this widget is big, and I'm pretty sure it stretches.
hbox = QHBoxLayout()
vbox.addLayout(hbox, 0)
self.n_button = QPushButton("&New training example")
self.connect(self.n_button, SIGNAL('clicked()'), self.on_new_example)
self.i_button = QPushButton("&Infer")
self.connect(self.i_button, SIGNAL('clicked()'), self.on_infer)
self.t_button = QPushButton("&Train")
self.connect(self.t_button, SIGNAL('clicked()'), self.on_train)
hbox.addWidget(QLabel("Training example: "), 0)
self.example_number = QTextEdit()
self.example_number.setLineWrapMode(0)#QPlainTextEdit.NoWrap)
hbox.addWidget(self.example_number, 0)
hbox.addWidget(self.n_button, 0)
hbox.addWidget(self.i_button, 0)
hbox.addWidget(self.t_button, 0)
hbox.addSpacing(1)
If you want one line only, you should use QLineEdit. Your buttons have Preferred size policy, which keeps them at a fixes size. The QTextEdit probably has MinimumExpanding or Expanding, and thus takes up the rest of the available space.

Resources