How do I Update on Qwidget? - mysql-connector

I wanna create a QWidget with 2 button and 1 label where this widget will be connected with a database in PYQT6. Now 1st button will move to previous data and 2nd button will move to next data and in the label I'll show the save image in that particular img save in that selected column of that database. I created a dbms and also create my desire widget but now I can't connecting the buttons and the dbms. Here the code I
progress.
import mysql.connector as mc
from PyQt6 import QtCore, QtGui, QtWidgets
class Ui_Form(object):
def setupUi(self, Form):
Form.setObjectName("Form")
Form.resize(511, 447)
self.label_3 = QtWidgets.QLabel(parent=Form)
self.label_3.setGeometry(QtCore.QRect(110, 100, 281, 241))
self.label_3.setText("")
self.label_3.setObjectName("label_3")
self.previous = QtWidgets.QPushButton(parent=Form)
self.previous.setGeometry(QtCore.QRect(20, 380, 111, 31))
self.previous.setObjectName("previous")
self.next = QtWidgets.QPushButton(parent=Form)
self.next.setGeometry(QtCore.QRect(374, 380, 111, 31))
self.next.setObjectName("next")
self.widget = QtWidgets.QWidget(parent=Form)
self.widget.setGeometry(QtCore.QRect(30, 40, 188, 22))
self.widget.setObjectName("widget")
self.horizontalLayout = QtWidgets.QHBoxLayout(self.widget)
self.horizontalLayout.setContentsMargins(0, 0, 0, 0)
self.horizontalLayout.setObjectName("horizontalLayout")
self.point1 = QtWidgets.QLabel(parent=self.widget)
self.point1.setObjectName("point1")
self.horizontalLayout.addWidget(self.point1)
self.lineEdit = QtWidgets.QLineEdit(parent=self.widget)
self.lineEdit.setObjectName("lineEdit")
self.horizontalLayout.addWidget(self.lineEdit)
self.widget1 = QtWidgets.QWidget(parent=Form)
self.widget1.setGeometry(QtCore.QRect(290, 40, 188, 22))
self.widget1.setObjectName("widget1")
self.horizontalLayout_2 = QtWidgets.QHBoxLayout(self.widget1)
self.horizontalLayout_2.setContentsMargins(0, 0, 0, 0)
self.horizontalLayout_2.setObjectName("horizontalLayout_2")
self.point2 = QtWidgets.QLabel(parent=self.widget1)
self.point2.setObjectName("point2")
self.horizontalLayout_2.addWidget(self.point2)
self.lineEdit_2 = QtWidgets.QLineEdit(parent=self.widget1)
self.lineEdit_2.setObjectName("lineEdit_2")
self.horizontalLayout_2.addWidget(self.lineEdit_2)
self.retranslateUi(Form)
QtCore.QMetaObject.connectSlotsByName(Form)
def select_current(self):
self.rowcount = self.setRowCount(1)
self.colcount = self.setColCount(1)
def check_database(self):
try:
self.mydb = mc.connect(
host="localhost",
user="root",
password="",
database="dataimage"
)
self.tablename = "users"
mycursor = mydb.cursor()
except mc.Error as e:
self.label_3.setText("Error found")
def move_previous(self):
cursor = mydb.cursor
cursor.execute("SELECT Xpoint FROM {}".format(tablename))
self.result= self.mycursor.fetchall()
print(self.colcount.Xpoint)
def retranslateUi(self, Form):
_translate = QtCore.QCoreApplication.translate
Form.setWindowTitle(_translate("Form", "Form"))
self.previous.setText(_translate("Form", "Previous"))
self.next.setText(_translate("Form", "Next"))
self.point1.setText(_translate("Form", "X_Point"))
self.point2.setText(_translate("Form", "Y_Point"))
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
Form = QtWidgets.QWidget()
ui = Ui_Form()
ui.setupUi(Form)
Form.show()
sys.exit(app.exec())
Expecting that my button will move base on my data on database and will show the save img on that data on that col.

Related

How to get bounding box with text using Tesseract4Android?

I am using 'cz.adaptech.tesseract4android:tesseract4android:4.3.0' in my Android project.
Is it possible to get bounding box with text data like in example below?
(32, 24, 60, 17) Maitre
(100, 24, 82, 19) corbeau,
(191, 28, 29, 13) sur
(227, 28, 22, 12) un
(257, 24, 50, 17) arbre
(315, 24, 70, 21) perché,
(79, 49, 58, 17) Tenait
Official sample shows how to get plain text only, not boxes with text inside:
TessBaseAPI tess = getTessBaseAPI(path, context);
String text = tess.getUTF8Text();
To get bounding box with text use next code:
TessBaseAPI tess = new TessBaseAPI();
// Given path must contain subdirectory `tessdata` where are `*.traineddata` language files
String dataPath = context.getExternalFilesDir(null).getPath() + "/OCRme/";
// Initialize API for specified language (can be called multiple times during Tesseract lifetime)
if (!tess.init(dataPath, "eng", TessBaseAPI.OEM_TESSERACT_LSTM_COMBINED)) {
throw new IOException("Error initializing Tesseract (wrong data path or language)");
}
// Specify image and then recognize it and get result (can be called multiple times during Tesseract lifetime)
tess.setImage(bitmap);
tess.setPageSegMode(TessBaseAPI.PageSegMode.PSM_AUTO_OSD);
tess.getUTF8Text();
ResultIterator resultIterator = tess.getResultIterator();
List < Rect > boxes = new ArrayList < > ();
List < String > texts = new ArrayList < > ();
while (resultIterator.next(TessBaseAPI.PageIteratorLevel.RIL_WORD)) {
Rect rect = resultIterator.getBoundingRect(TessBaseAPI.PageIteratorLevel.RIL_WORD);
String text = resultIterator.getUTF8Text(TessBaseAPI.PageIteratorLevel.RIL_WORD);
boxes.add(rect);
texts.add(text);
}

is there something i'm missing in displaying plotOutput() (bs4Dash)

library(shiny)
library(gapminder)
library(bbplot)
library(tidyverse)
library(bs4Dash)
year_range <- range(gapminder[["year"]])
ui <- dashboardPage(
header = dashboardHeader(
title = dashboardBrand(
title = "LE",
color = "gray"
)
),
sidebar = dashboardSidebar(
width = ,
skin = "light",
sidebarMenu(
id = "sidemenu",
menuItem(
"plotme",
tabName = "plotme",
icon = icon("sliders")
)
)
),
body = dashboardBody(
tabItem(
tabItem(
tabName = "plotme",
fluidRow(
column(
width = 12,
plotOutput("plotme")
)
)
)
)
),
controlbar = dashboardControlbar(
collapsed = FALSE,
pinned = TRUE,
skin = "light",
controlbarMenu(
id = "plotme",
controlbarItem(
title = "Filter:",
selectInput("continent", "Continent",
choices = unique(gapminder$continent)),
selectInput("country", "Country",
choices = NULL),
sliderInput("year",
"Select The Year Range:",
min = year_range[[1]],
max = year_range[[2]],
value = c(year_range[[1]], year_range[[2]]),
sep = "",
step = 1)
)
)
),
)
server <- function(input, output, session) {
continent_data <- reactive({
gapminder %>%
filter(continent == input$continent
& year >= input$year[[1]] | year <= input$year[[2]])
})
observeEvent(continent_data(), {
freezeReactiveValue(input, "country")
choices <- unique(continent_data()$country)
updateSelectInput(session, "country", choices = choices)
})
country_data <- reactive({
req(input$continent)
continent_data() %>%
filter(country == input$country
& year >= input$year[[1]] & year <= input$year[[2]])
})
output$plot <- renderPlot({
req(input$country)
ggplot(country_data(), aes(year, lifeExp)) +
geom_line(colour = "#1380A1", size = 1) +
geom_hline(yintercept = 0, size = 1, colour="#333333")
}, res = 96)
}
shinyApp(ui = ui, server = server)
I have checked the reactive elements and it seems fine. My guess is the issue might be from the menuItems() or from dashboardcontrolbar()
The UI is displaying alright but the plotOutput is not showing
I have checked the reactive elements and it seems fine. My guess is the issue might be from the menuItems() or from dashboardcontrolbar()
The UI is displaying alright but the plotOutput is not showing
I didn't try the app but maybe the problem is with the id's.
You are using plotOutput("plotme") in the UI and output$plot in the server function.

pyglet label not showing on screen on draw() with OpenAI gym render

I'm using a wrapper of OpenAI gym to create a graphical representation of a problem. For that, I'm drawing a circle with the given wrapper and then try to add some text.
My issue is, that only the circle shows, but the text label does not appear. Any suggestions on how I can make the text visible would be highly appreciated. Below a minimal example, that show the problem:
import pyglet
from gym.envs.classic_control import rendering
screen_width = 600
screen_height = 400
table_radius = 200
viewer = rendering.Viewer(screen_width, screen_height + 20)
table = rendering.make_circle(radius=table_radius, filled=False)
table_trans = rendering.Transform()
table.add_attr(table_trans)
table_trans.set_translation(screen_width / 2, screen_height / 2)
viewer.add_geom(table)
text = 'This is a test but it is not visible'
label = pyglet.text.Label(text, font_size=36,
x=10, y=10, anchor_x='left', anchor_y='bottom',
color=(255, 123, 255, 255))
label.draw()
viewer.render(return_rgb_array=False)
input()
What worked for me is to manually implement the render function and insert the label after the tranform.disable()
## Content of the render function
glClearColor(1, 1, 1, 1)
self.viewer.window.clear()
self.viewer.window.switch_to()
self.viewer.window.dispatch_events()
self.viewer.transform.enable()
for geom in self.viewer.geoms:
geom.render()
for geom in self.viewer.onetime_geoms:
geom.render()
self.viewer.transform.disable()
# Text
label = pyglet.text.Label(
"Hello, world",
font_name="Times New Roman",
font_size=36,
x=100,
y=100,
anchor_x="center",
anchor_y="center",
color=(255, 0, 0, 255),
)
label.draw()
arr = None
...
please try this code:
import pyglet
from gym.envs.classic_control import rendering
class DrawText:
def __init__(self, label:pyglet.text.Label):
self.label=label
def render(self):
self.label.draw()
screen_width = 600
screen_height = 400
table_radius = 200
viewer = rendering.Viewer(screen_width, screen_height + 20)
table = rendering.make_circle(radius=table_radius, filled=False)
table_trans = rendering.Transform()
table.add_attr(table_trans)
table_trans.set_translation(screen_width / 2, screen_height / 2)
viewer.add_geom(table)
text = 'This is a test but it is not visible'
label = pyglet.text.Label(text, font_size=36,
x=10, y=10, anchor_x='left', anchor_y='bottom',
color=(255, 123, 255, 255))
label.draw()
viewer.add_geom(DrawText(label))
viewer.render(return_rgb_array=False)
input()

wxPython popup / tooltip on a wx.DrawRectangle?

In the code below, DrawRect1 and DrawRect2 represent a simplified version of functions that draw multiple shapes on screen.
I want to display some supplementary information if I hover over any of the drawn rectangles (similar to the way a tooltip works). But I need to generate that display information from a function rather than static definition.
Given I know the coords of the draw rectangle, can I either create another type of object with the same coords, or link a hover action to each drawnrectangle, so that I could call a function defined something like this ? :
EDIT: I guess I need a object I can bind a wx.EVT_ENTER_WINDOW event to, that I can create at the same time as dc.DrawRectangle ? Or can I bind this handler to the panel and use x,y position to try and match to a list of drawn rectangle coords ?
The closest thing I could find on SO was this old question, wxpython tooltip at specific coordinates but it wasn't a comprehensive answer.
import wx
class Mywin(wx.Frame):
def __init__(self, parent, title):
super(Mywin, self).__init__(parent, title=title, size=(500, 300))
self.InitUI()
def InitUI(self):
self.panel = wx.Panel(self)
self.panel.SetBackgroundColour(wx.Colour('RED'))
self.Centre()
self.Show(True)
menuBar = wx.MenuBar()
RectangleButton = wx.Menu()
Item1 = RectangleButton.Append(wx.ID_ANY, 'Rectangle 1')
Item2 = RectangleButton.Append(wx.ID_ANY, 'Rectangle 2')
menuBar.Append(RectangleButton, 'Rectangles')
self.SetMenuBar(menuBar)
self.Bind(wx.EVT_MENU, self.DrawRect1, Item1)
self.Bind(wx.EVT_MENU, self.DrawRect2, Item2)
def DrawRect1(self, e):
self.panel.SetBackgroundColour(wx.Colour('BLUE'))
self.Refresh()
self.Update()
self.dc = wx.ClientDC(self.panel)
self.dc.SetBrush(wx.Brush(wx.Colour('white')))
self.dc.DrawRectangle(10, 10, 100, 100)
def DrawRect2(self, e):
self.panel.SetBackgroundColour(wx.Colour('GREEN'))
self.Refresh()
self.Update()
self.dc = wx.ClientDC(self.panel)
self.dc.SetBrush(wx.Brush(wx.Colour('white')))
self.dc.DrawRectangle(20, 20, 50, 50)
myApp = wx.App()
Mywin(None,'Drawing demo')
myApp.MainLoop()
A DC doesn't appear to support adding a tooltip, which is annoying, especially as the underlying wx widget appears to, as far as I can tell from the docs.
The best I can come up with at the moment, is to track the mouse movements but it is far from satisfactory and I suspect so limited that it might not be any help.
With those caveats made, I've supplied 3 options for the ToolTip like display. Namely, setting and unsetting the tooltip of the panel itself, a statusbar entry and a popup window.
Discard any you don't require.
import wx
class Mywin(wx.Frame):
def __init__(self, parent, title):
super(Mywin, self).__init__(parent, title=title, size=(500, 300))
self.tips = ["","Rectangle 1","Rectangle 2"]
self.rect = []
self.InitUI()
def InitUI(self):
self.panel = wx.Panel(self)
self.panel.SetBackgroundColour(wx.Colour('RED'))
self.Centre()
self.Show(True)
menuBar = wx.MenuBar()
RectangleButton = wx.Menu()
self.status = self.CreateStatusBar()
self.status.SetFieldsCount(number=2)
Item1 = RectangleButton.Append(wx.ID_ANY, 'Rectangle 1')
Item2 = RectangleButton.Append(wx.ID_ANY, 'Rectangle 2')
menuBar.Append(RectangleButton, 'Rectangles')
self.SetMenuBar(menuBar)
self.Bind(wx.EVT_MENU, self.DrawRect1, Item1)
self.Bind(wx.EVT_MENU, self.DrawRect2, Item2)
self.panel.Bind(wx.EVT_MOTION, self.MouseMovement)
def DrawRect1(self, e):
self.panel.SetBackgroundColour(wx.Colour('BLUE'))
self.Update()
self.dc = wx.ClientDC(self.panel)
self.dc.SetBrush(wx.Brush(wx.Colour('white')))
self.dc.DrawRectangle(10, 20, 100, 200)
#Note the position of the DC
self.rect = [x for x in self.dc.BoundingBox]
#Append the id
self.rect.append(1)
def DrawRect2(self, e):
self.panel.SetBackgroundColour(wx.Colour('GREEN'))
self.Update()
self.dc = wx.ClientDC(self.panel)
self.dc.SetBrush(wx.Brush(wx.Colour('white')))
self.dc.DrawRectangle(20, 20, 50, 50)
self.rect = [x for x in self.dc.BoundingBox]
self.rect.append(2)
def MouseMovement(self, event):
x,y = event.GetPosition()
self.panel.SetToolTip('')
self.status.SetStatusText('', 1)
if self.rect:
if x >= self.rect[0] and x <= self.rect[2] and y >= self.rect[1] and y <= self.rect[3]:
self.panel.SetToolTip(self.tips[self.rect[4]])
self.status.SetStatusText("Hovering over "+self.tips[self.rect[4]], 1)
win = Popup(self,self.rect[4],self.tips[self.rect[4]])
pos = self.GetScreenPosition()
win.Position(pos,(-1,-1))
win.Popup()
class Popup(wx.PopupTransientWindow):
def __init__(self, parent, id, id_text):
wx.PopupTransientWindow.__init__(self, parent)
panel = wx.Panel(self)
panel.SetBackgroundColour("gold")
text = wx.StaticText(panel, -1,
"This is a wx.PopupTransientWindow\n"
"Click mouse outside of it\n\n"
"Id of widget is "+str(id)+"\n"
"You are hovering over "+id_text)
# add other widgets here if required
sizer = wx.BoxSizer(wx.VERTICAL)
sizer.Add(text, 0, wx.ALL, 5)
panel.SetSizer(sizer)
sizer.Fit(panel)
sizer.Fit(self)
self.Layout()
myApp = wx.App()
Mywin(None,'Drawing demo')
myApp.MainLoop()

Laziness in ScalaFX nodes

Here is an example from Pro ScalaFX:
package proscalafx.ch02.stagecoach
import scalafx.Includes._
import scalafx.application.JFXApp
import scalafx.application.JFXApp.PrimaryStage
import scalafx.beans.property.StringProperty
import scalafx.geometry.VPos
import scalafx.scene.control.{Button, CheckBox, Label, TextField}
import scalafx.scene.input.MouseEvent
import scalafx.scene.layout.{HBox, VBox}
import scalafx.scene.paint.Color
import scalafx.scene.shape.Rectangle
import scalafx.scene.text.Text
import scalafx.scene.{Group, Scene}
import scalafx.stage.{Screen, StageStyle}
/** Stage property example.
*
* Can be run with various command line parameters to control stage style:
* decorated - a solid white background and platform decorations (default).
* transparent - transparent background and no decorations.
* undecorated - a solid white background and no decorations.
* utility - a solid white background and minimal platform decorations used for a utility window.
* #author Rafael
*/
object StageCoachMain extends JFXApp {
val titleProperty = StringProperty("")
// Process command line parameters
val stageStyle = parameters.unnamed match {
case Seq("transparent") => StageStyle.TRANSPARENT
case Seq("undecorated") => StageStyle.UNDECORATED
case Seq("utility") => StageStyle.UTILITY
case _ => StageStyle.DECORATED
}
lazy val textStageX = new Text {
textOrigin = VPos.Top
}
lazy val textStageY = new Text {
textOrigin = VPos.Top
}
lazy val textStageW = new Text {
textOrigin = VPos.Top
}
lazy val textStageH = new Text {
textOrigin = VPos.Top
}
lazy val textStageF = new Text {
textOrigin = VPos.Top
}
lazy val checkBoxResizable = new CheckBox {
text = "resizable"
// disable = stageStyle == StageStyle.TRANSPARENT || stageStyle == StageStyle.UNDECORATED
}
lazy val checkBoxFullScreen = new CheckBox {
text = "fullScreen"
}
lazy val titleTextField = new TextField {
text = "Stage Coach"
prefColumnCount = 15
}
stage = new PrimaryStage {
resizable = false
title <== titleProperty
scene = new Scene(370, 370) {
fill = Color.Transparent
root = new Group {
children = List(
new Rectangle {
width = 350
height = 350
arcWidth = 50
arcHeight = 50
fill = Color.SkyBlue
},
new VBox {
layoutX = 30
layoutY = 20
spacing = 10
children = List(
textStageX,
textStageY,
textStageW,
textStageH,
textStageF,
checkBoxResizable,
checkBoxFullScreen,
new HBox {
spacing = 10
children = List(
new Label("title:"),
titleTextField)
},
new Button {
text = "toBack()"
onAction = handle {stage.toBack()}
},
new Button {
text = "toFront()"
onAction = handle {stage.toFront()}
},
new Button {
text = "close()"
onAction = handle {stage.close()}
}
)
}
)
}
}
}
//when mouse button is pressed, save the initial position of screen
val rootGroup = stage.scene().content(0)
var dragAnchorX = 0.0
var dragAnchorY = 0.0
rootGroup.onMousePressed = (me: MouseEvent) => {
dragAnchorX = me.screenX - stage.x.value
dragAnchorY = me.screenY - stage.y.value
}
rootGroup.onMouseDragged = (me: MouseEvent) => {
stage.x = me.screenX - dragAnchorX
stage.y = me.screenY - dragAnchorY
}
textStageX.text <== new StringProperty("x: ") + stage.x.asString
textStageY.text <== new StringProperty("y: ") + stage.y.asString
textStageW.text <== new StringProperty("width: ") + stage.width.asString
textStageH.text <== new StringProperty("height: ") + stage.height.asString
textStageF.text <== new StringProperty("focused: ") + stage.focused.asString
stage.resizable = false
// NOTE: Due to a bug in JavaFX (2.2.3+) Stage.resizableProperty(), cannot directly use binding here,
// see http://javafx-jira.kenai.com/browse/RT-25942
// TODO: Revert to binding once JavaFX bug is corrected
// stage.resizable <==> checkBoxResizable.selected
checkBoxResizable.selected.onChange {
// To avoid using resizableProperty, use delegate.setResizable()
// stage.resizable = checkBoxResizable.selected.get
stage.delegate.setResizable(checkBoxResizable.selected())
}
checkBoxFullScreen.onAction = handle {
stage.fullScreen = checkBoxFullScreen.selected()
}
stage.title <== titleTextField.text
stage.initStyle(stageStyle)
stage.onCloseRequest = handle {println("Stage is closing")}
val primScreenBounds = Screen.primary.visualBounds
stage.x = (primScreenBounds.width - stage.width()) / 2
stage.y = (primScreenBounds.height - stage.height()) / 2
}
If I remove lazy before these Text objects, the app seems to works exactly the same as before. For example the textStageX object should show x-coordinate of the stage in real-time, and it still does without being lazy. So, what purpose does lazy serve here?
Another problem is that these lines of code
val primScreenBounds = Screen.primary.visualBounds
stage.x = (primScreenBounds.width - stage.width()) / 2
stage.y = (primScreenBounds.height - stage.height()) / 2
seems to intend to place the window at the center of the primary screen, but fails to do so (on OS X 10.10, with Java 1.8 and Scala 2.11.7).
lazy in unnecessary here. It is used in JFXApp if there are initialization order issues.
For the centering to work. The stage has to be shown first. I am not sure it this new in JavaFX 8 or there was a bug in original StageCoachMain code. Just add:
stage.show()
before the last three lines. You can also replace them with simply:
stage.centerOnScreen()
Thanks for pointing this out. I cleaned up the code in ProScalaFX repo.