I have needed to create a tool that can gather pixel values for the corners of a box of an image. I have decided to use PyQt5 for this as it is what I am most familiar with. I have used QPixmap for this and the scaled function to scale an image for zooming in and out with the scroll wheel. When I zoom however, the zoom always zooms to the same point and I am struggling to find a way to change the zoom origin. Thanks
import numpy
from matplotlib import pyplot as plt
from PyQt5.QtCore import QDate, Qt, QTime, QDateTime, QPoint, QRect, QSize, Qt
from PyQt5.QtWidgets import (QMainWindow, QWidget, QCalendarWidget,
QLabel, QApplication, QVBoxLayout, QTextEdit,
QFileDialog, QAction, QPushButton, QHBoxLayout,
QGridLayout, QInputDialog, QLineEdit, QTextEdit,
QPlainTextEdit, QRubberBand)
from PyQt5.QtGui import QIcon, QPixmap
import os, sys
class App(QWidget):
def __init__(self):
super().__init__()
self.title = 'BoundingBoxQT'
self.left = 1000
self.top = 100
self.width = 748
self.height = 1402
self.initUI()
def initUI(self):
self.setWindowTitle(self.title)
self.setGeometry(self.left, self.top, self.width, self.height)
# Create widget
self.label = QLabel(self)
self.pixmap = QPixmap('BALMRCRTLOA_trisected.png')
self.label.setPixmap(self.pixmap)
self.label.resize(self.pixmap.width(),self.pixmap.height())
self.show()
#getting the positio of the mouse click
self.mousePressEvent = self.ClickPosition
self.mouseReleaseEvent = self.ReleasePosition
self.mouseMoveEvent = self.Move
self._band = QRubberBand(QRubberBand.Rectangle, self)
self._band.show()
self.scale = 1
self.wheelEvent = self.ScrollWheel
self.scrollcount = 0
def ClickPosition(self, event):
self.origin = event.pos()
x = event.pos().x()
y = event.pos().y()
print(x,y)
def Move(self, event):
self._band.setGeometry(QRect(self.origin, event.pos()).normalized())
def ReleasePosition(self, event):
x = event.pos().x()
y = event.pos().y()
print(x,y)
def ScrollWheel(self,event):
result = event.angleDelta().y()
x = event.pos().x()
y = event.pos().y()
if result < 0:
self.zoom_out(self.wheelEvent,x,y)
elif result > 0:
self.zoom_in(self.wheelEvent,x,y)
def zoom_in(self,event,x,y):
if self.scrollcount == 7:
return
self.scale *= 1.5
self.scrollcount += 1
self.resize(x,y)
def zoom_out(self,event,x,y):
if self.scrollcount == 0:
return
self.scale /= 1.5
self.scrollcount -= 1
self.resize(x,y)
def resize(self,x,y):
size = self.label.size() # maybe remove the self if wrong
scaled = self.pixmap.scaled(self.scale*size)
self.label.setPixmap(scaled)
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = App()
sys.exit(app.exec_())
Related
The window shows a set of pictures. Once the window is maximized the app shows all pics in the window so it resizes every image looking ugly. I'd like to prevent the streching and keep the aspect ratio. Any clue?
This is the code of the proof of concept:
QApplication, QListWidget, QAbstractItemView, QPushButton, QWidget,
QTabWidget, QVBoxLayout, QHBoxLayout, QLabel, QPlainTextEdit,
QTextEdit, QCheckBox, QFileDialog, QMessageBox, QGridLayout from
PyQt5.QtCore import QProcess, QTimer, Qt from PyQt5.QtGui import QFont, QPixmap import os from QLabelClickable import QLabelClickable
class ExampleApp(QMainWindow):
def __init__(self):
super().__init__()
self.title = 'Example'
self.left = 0
self.top = 0
self.width = 1000
self.height = 800
self.setMaximumWidth(1000)
self.setMaximumHeight(800)
self.setWindowTitle(self.title)
self.setGeometry(self.left, self.top, self.width, self.height)
self.show()
data = []
for root, dirs, files in os.walk('img/'):
for file in files:
filepath = os.path.join(root, file)
data.append(filepath)
self.picture_window = PictureWindow(data=data)
self.picture_window.show()
class PictureWindow(QWidget):
def __init__(self, data):
super().__init__()
self.n_columns = 5
self.data = data
self.gridLayout = QGridLayout()
for i, filename in enumerate(self.data):
self.render_picture(filename=filename, pos=i)
self.setLayout(self.gridLayout)
def render_picture(self, filename, pos):
image_widget = QLabelClickable(pos)
image_widget.setGeometry(15, 15, 118, 130)
image_widget.setToolTip(filename)
image_widget.setCursor(Qt.PointingHandCursor)
self.pixmapImagen = QPixmap(filename).scaled(375, 375, Qt.KeepAspectRatio, Qt.SmoothTransformation)
image_widget.setPixmap(self.pixmapImagen)
image_widget.setAlignment(Qt.AlignCenter)
cell_layout = QVBoxLayout()
cell_layout.setAlignment(Qt.AlignHCenter)
cell_layout.addWidget(image_widget)
self.gridLayout.addLayout(cell_layout, int(pos / self.n_columns), pos % self.n_columns)
from PyQt5.QtCore import Qt, pyqtSignal, QTimer
from PyQt5.QtWidgets import QApplication, QDialog, QLabel, QMessageBox
class QLabelClickable(QLabel):
clicked = pyqtSignal(str)
def __init__(self, id, parent=None):
super(QLabelClickable, self).__init__(parent)
self.id = id
def mousePressEvent(self, event):
self.ultimo = "Click"
def mouseReleaseEvent(self, event):
if self.ultimo == "Click":
QTimer.singleShot(QApplication.instance().doubleClickInterval(),
self.performSingleClickAction)
else:
self.clicked.emit(self.ultimo+"-"+str(self.id))
def mouseDoubleClickEvent(self, event):
self.ultimo = "Double Click"
def performSingleClickAction(self):
if self.ultimo == "Click":
self.clicked.emit(self.ultimo+"-"+str(self.id))
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = ExampleApp()
sys.exit(app.exec_())
This is how it looks when window is normal:
And looks like this when window is maximized:
After a few days trying to figure out what's going on here I an't go further, could you please help me to spot anything wrong?
I expect the pics to keepe their aspect ratio to implement a ScrollArea later on.
The code below sketches a polygon on an image. I would like to draw a second identical shape inside the primary one with a gap of 0.3m. I have tried a couple of solutions but none of them worked in all use cases.
Please refer to the attached screenshot.
Context: The shape is drawn by combining a group of selected points using the QPolygon class.
import sys
from sympy import Polygon
from PyQt5.QtWidgets import QApplication, QWidget, QHBoxLayout, QVBoxLayout
from PyQt5.QtCore import QLine, Qt, QPoint, QRect
from PyQt5.QtGui import QPixmap, QPainter,QColor,QPolygon
from PyQt5 import QtCore, QtGui, QtWidgets, uic
class MyApp(QWidget):
def __init__(self):
super().__init__()
self.window_width, self.window_height =1200,800
self.setMinimumSize(self.window_width,self.window_height)
layout= QVBoxLayout()
self.setLayout(layout)
self.pix = QPixmap('image.jpg')
self.resize(self.pix.width(),self.pix.height())
# self.pix.fill(Qt.white)
# tableau
self.point = QPoint()
self.tab =[]
def paintEvent(self,event):
painter = QPainter(self)
pen = QtGui.QPen()
pen.setColor(QtGui.QColor('red'))
pen.setWidth(3)
painter.setPen(pen)
painter.drawPixmap(QPoint(),self.pix)
if not self.point.isNull():
# rect = QRect(self.begin,self.destination)
# painter.drawRect(rect.normalized())
line = QPoint(self.point)
painter.drawPoint(line)
def mousePressEvent(self,event):
if event.buttons() & Qt.LeftButton:
self.point = event.pos()
# self.destination = self.begin
self.update()
# def mouseMoveEvent(self,event):
# if event.buttons() & Qt.LeftButton:
# self.point = event.pos()
# self.update()
def mouseReleaseEvent(self,event):
pen = QtGui.QPen()
painter = QPainter(self.pix)
if event.button() == Qt.LeftButton:
# rect = QRect(self.begin,self.destination)
line = QPoint(self.point)
pen.setColor(QtGui.QColor('red'))
pen.setWidth(3)
painter.setPen(pen)
painter.drawPoint(line)
painter.setPen(QColor(168, 34, 3))
self.tab.append(self.point)
print(self.point.x,self.point.y)
self.point = QPoint()
# w = (rect.width()*12.5)/1056
# h = (rect.height()*12.5/1056)
# a=w*h
# print(w, h,a)
self.update()
if event.button() == Qt.RightButton:
points = QPolygon(self.tab)
pen.setColor(QtGui.QColor('red'))
painter.setPen(pen)
painter.drawPolygon(points)
#print(self.tab[0])
polytab=[]
for i in self.tab:
polytab.append((i.x(),i.y()))
print(Polygon(*polytab).area*(12.5/1056)*(12.5/1056))
print((self.tab[0].x()-self.tab[1].x())*(12.5/1056))
self.tab=[]
self.update()
if __name__ == '__main__':
app = QApplication(sys.argv)
app.setStyleSheet('''QWidget{font-size:30px}''')
myAPP = MyApp()
myAPP.show()
try:
sys.exit(app.exec_())
except SystemExit:
print('Closing Window...')
The algorithm is given a vertex so the associated edges must be translated in a parallel way and the intersection of these lines is a point of the desired polygon.
import sys
from PyQt5.QtCore import QLineF
from PyQt5.QtGui import QColor, QPainter, QPen, QPolygonF
from PyQt5.QtWidgets import QApplication, QWidget
def calculate_inner_polygon(polygon, offset):
if polygon.count() < 3:
return QPolygonF()
points = []
for i in range(polygon.count()):
pp = polygon[(i - 1 + polygon.count()) % polygon.count()]
pc = polygon[i]
pn = polygon[(i + 1 + polygon.count()) % polygon.count()]
line_0 = QLineF(pp, pc)
normal_0 = line_0.normalVector()
normal_0.setLength(offset)
line_0.translate(normal_0.dx(), normal_0.dy())
line_1 = QLineF(pc, pn)
normal_1 = line_1.normalVector()
normal_1.setLength(offset)
line_1.translate(normal_1.dx(), normal_1.dy())
t, point = line_0.intersects(line_1)
if t != QLineF.NoIntersection:
points.append(point)
return QPolygonF(points)
class MyApp(QWidget):
def __init__(self):
super().__init__()
self.setMinimumSize(1200, 800)
self._points = list()
def paintEvent(self, event):
painter = QPainter(self)
painter.fillRect(self.rect(), QColor("white"))
if not self._points:
return
pen_width = 3
offset = -8
pen = QPen(QColor("red"))
outer_polygon = QPolygonF(self._points)
inner_polygon = calculate_inner_polygon(outer_polygon, offset)
for polygon in (outer_polygon, inner_polygon):
pen.setWidth(pen_width)
painter.setPen(pen)
painter.drawPolygon(polygon)
pen.setWidth(2 * pen_width)
painter.setPen(pen)
for point in polygon:
painter.drawPoint(point)
def mouseReleaseEvent(self, event):
self._points.append(event.pos())
self.update()
if __name__ == "__main__":
app = QApplication(sys.argv)
w = MyApp()
w.show()
sys.exit(app.exec_())
Im trying to develop a program which have many of my custom widget. in my widget i have a crosshair mouse pointer and when i move it in one of my widgets, all of them must sense it and the crosshair must react on every single widget.
I have a self.update() on the end of the paintEnent function.
How can i force the other widgets on my app to react it?
paintEvent is not a simple code like this and as i add every functions on this part, it make a very high CPU usage. How can i manage it?
import sys
from PyQt5.QtWidgets import QApplication, QDialog, QListWidget,
QComboBox, QVBoxLayout, QPushButton, QLabel, QMainWindow, QWidget,
QHBoxLayout, QVBoxLayout, QSizePolicy
from PyQt5.QtCore import Qt, QSize, QRect
from PyQt5.QtGui import QPalette, QColor, QPen, QPixmap, QPainter,
QBrush
class Boom(QWidget):
xPos=-1.0
def __init__(self,bgColor,xSpace=1,ySpace=1):
super().__init__()
self.bgColor=bgColor
self.x = -1
self.y = -1
self.setSizePolicy(QSizePolicy.MinimumExpanding,QSizePolicy.MinimumExpanding)
self.setMouseTracking(True)
layout = QVBoxLayout()
self.setLayout(layout)
def mouseMoveEvent(self, event):
global xPos
self.x = event.x()
self.y = event.y()
xPos=self.x/self.width()
self.update()
def paintEvent(self, e):
painter = QPainter(self)
font = painter.font()
font.setFamily('Times')
font.setPointSize(8)
painter.setFont(font)
brush = QBrush()
brush.setColor(QColor(self.bgColor))
brush.setStyle(Qt.SolidPattern)
pen = QPen()
pen.setWidth(1)
pen.setColor(QColor('black'))
painter.setPen(pen)
rect = QRect(0, 0, painter.device().width(), painter.device().height())
painter.fillRect(rect, brush)
pen.setColor(QColor('blue'))
painter.setPen(pen)
painter.drawLine(self.x, 0, self.x,painter.device().height()) #V
painter.drawLine(0, self.y, painter.device().width(),self.y) #H
self.update()
painter.end()
class MainWindow(QMainWindow):
def __init__(self):
super(MainWindow, self).__init__()
self.setWindowTitle("Graph")
MainPanelLayout = QHBoxLayout()
MainPanelLayout.setContentsMargins(1,1,1,1)
MainPanelLayout.setSpacing(1)
B1=Boom('pink',0)
B2=Boom('gray',1)
MainPanelLayout.addWidget(B1)
MainPanelLayout.addWidget(B2)
widget = QWidget()
widget.setLayout(MainPanelLayout)
self.setCentralWidget(widget)
if __name__ == "__main__":
app = QApplication(sys.argv)
mainWindow = MainWindow()
mainWindow.show()
# mainWindow.showMaximized()
app.exec_()
Iv found a way!
I used signal and slots to communicate between instances
May it works for others too :)
import sys
from PyQt5.QtWidgets import QApplication, QDialog, QListWidget,QComboBox, QVBoxLayout, QPushButton, QLabel, QMainWindow,QWidget, QHBoxLayout, QVBoxLayout, QSizePolicy
from PyQt5.QtCore import Qt, QSize, QRect, QObject, pyqtSignal
from PyQt5.QtGui import QPalette, QColor, QPen, QPixmap, QPainter,QBrush
import FxMainForm
class BoomCommunicate(QObject):
signal = pyqtSignal()
class Boom(QWidget):
xPos=-1
def __init__(self,bgColor,nChannel=-1,xSpace=1,ySpace=1):
super().__init__()
self.bgColor=bgColor
self.xSpace=xSpace
self.ySpace=ySpace
self.x = -1
self.y = -1
self.nChannel=nChannel
self.setSizePolicy(QSizePolicy.MinimumExpanding,QSizePolicy.MinimumExpanding)
self.setMouseTracking(True)
self.layout = QVBoxLayout()
self.setLayout(self.layout)
self.communicate = BoomCommunicate()
self.communicate.signal.connect(self.trigger_refresh)
def mouseMoveEvent(self, event):
self.x = event.x()
self.y = event.y()
if self.nChannel==0:
Boom.xPos=self.x/self.width()
self.communicate.signal.emit()
def paintEvent(self, e):
painter = QPainter(self)
font = painter.font()
font.setFamily('Times')
font.setPointSize(8)
painter.setFont(font)
brush = QBrush()
brush.setColor(QColor(self.bgColor))
brush.setStyle(Qt.SolidPattern)
pen = QPen()
pen.setWidth(1)
pen.setColor(QColor('black'))
painter.setPen(pen)
## Border
rect = QRect(0, 0, painter.device().width(), painter.device().height())
painter.fillRect(rect, brush)
pen.setColor(QColor('blue'))
painter.setPen(pen)
# self.Drawings(painter,pen,brush)
if self.nChannel==0:
painter.setPen(QPen(Qt.red, 1, Qt.SolidLine))
painter.drawLine(self.x, self.ySpace, self.x,painter.device().height()-self.ySpace-1) ##V
painter.drawLine(self.xSpace, self.y, painter.device().width()-self.ySpace-1,self.y) ##H
if not FxMainForm.studyItem==None:
painter.setPen(QPen(Qt.black, 1, Qt.SolidLine))
painter.drawText(5, 15,FxMainForm.studyItem[0]+' ('+FxMainForm.studyItem[1]+') ')
Boom.xPos=self.x/self.width()
else:
painter.setPen(QPen(Qt.red, 1, Qt.SolidLine))
painter.drawLine(int(Boom.xPos*painter.device().width()), self.ySpace,int(Boom.xPos*painter.device().width()),painter.device().height()-self.ySpace-1)
painter.end()
def trigger_refresh(self):
self.update()
def sizeHint(self):
return QSize(100, 100)
class MainWindow(QMainWindow):
def __init__(self):
super(MainWindow, self).__init__()
self.setWindowTitle("Graph-Boom")
self.MainPanelLayout = QHBoxLayout()
self.MainPanelLayout.setContentsMargins(1,1,1,1)
self.MainPanelLayout.setSpacing(1)
self.B1=Boom('pink',0)
self.B2=Boom('gray',1)
self.MainPanelLayout.addWidget(self.B1)
self.MainPanelLayout.addWidget(self.B2)
self.B1.communicate.signal.connect(self.B2.update)
self.widget = QWidget()
self.widget.setLayout(self.MainPanelLayout)
self.setCentralWidget(self.widget)
if __name__ == "__main__":
app = QApplication(sys.argv)
mainWindow = MainWindow()
mainWindow.show()
# mainWindow.showMaximized()
app.exec_()
I am trying to build a paint app that has a grid, but I don't want to grid to be included in the saved photo.
I tried to draw on a transparent image, but I got a black background instead!
Here is the full code:
import sys
from PyQt5 import QtGui, QtWidgets, QtCore
from PyQt5.QtCore import QPoint, Qt
from PyQt5.QtGui import QBrush, QGuiApplication, QImage, QPainter, QPen, QIcon, QColor
from PyQt5.QtWidgets import QApplication, QMainWindow, QVBoxLayout, QWidget, QTextEdit, QAction, QFileDialog,
QGraphicsScene, QGraphicsProxyWidget, QGraphicsView
import pyautogui
import matplotlib.pyplot as plt
class Drawer(QWidget):
def __init__(self, parent=None):
super().__init__(parent)
self._drawing = False
self.last_point = QPoint()
self.image_layer = QImage(self.size(), QImage.Format_RGB32)
self.image_layer.fill(Qt.gray)
self.brushSize = 2
self.brushColor = Qt.black
#paint = QPainter(self.image_layer)
#paint.setCompositionMode(QtGui.QPainter.CompositionMode_Clear)
# paint.drawLine(0,0,self.size().width(),0)
# paint.drawLine(0,10,200,10)
#paint.drawLine(0,0,0,200)
#paint.drawLine(10,0,10,200)
self.update()
def mousePressEvent(self, event):
self._drawing = True
self.last_point = event.pos()
def mouseMoveEvent(self, event):
if self._drawing and event.buttons() & Qt.LeftButton:
painter = QPainter(self.image_layer)
painter.setPen(
QPen(
self.brushColor,
self.brushSize,
Qt.SolidLine,
Qt.RoundCap,
Qt.RoundJoin,
)
)
painter.drawLine(self.last_point, event.pos())
self.last_point = event.pos()
self.update()
def paintEvent(self, event):
painter = QPainter(self)
painter.drawImage(QPoint(), self.image_layer)
painter.end()
def resizeEvent(self, event):
if (
self.size().width() > self.image_layer.width()
or self.size().height() > self.image_layer.height()
):
qimg = QImage(
max(self.size().width(), self.image_layer.width()),
max(self.size().height(), self.image_layer.height()),
QImage.Format_RGB32,
)
qimg.fill(Qt.gray)
painter = QPainter(qimg)
painter.drawImage(QPoint(), self.image_layer)
painter.drawLine(0, 0, qimg.size().width(), 0)
painter.drawLine(0, 10, qimg.size().width(), 10)
painter.drawLine(0, 600, qimg.size().width(), 600)
print(qimg.size().height())
painter.end()
self.image_layer = qimg
self.update()
class Window(QMainWindow):
def __init__(self, parent=None):
super().__init__(parent)
[x, y] = pyautogui.size()
self.setGeometry(0, 0, x, y)
self.drawer = Drawer()
textbox = QTextEdit("Converted text will show here")
central_widget = QWidget()
self.setCentralWidget(central_widget)
vlay = QVBoxLayout(central_widget)
vlay.addWidget(textbox)
vlay.addWidget(self.drawer, stretch=1)
mainMenu = self.menuBar()
fileMenu = mainMenu.addMenu("File")
saveAction = QAction(QIcon("icons/save.png"), "Save", self)
saveAction.setShortcut("Ctrl+S")
fileMenu.addAction(saveAction)
saveAction.triggered.connect(self.save)
def save(self):
filePath, _ = QFileDialog.getSaveFileName(self.drawer, "Save Image", "",
"PNG(*.png);;JPEG(*.jpg *.jpeg);;All Files(*.*) ")
if filePath == "":
return
self.drawer.image_layer.save(filePath)
if __name__ == "__main__":
app = QApplication(sys.argv)
window = Window()
window.show()
sys.exit(app.exec())
Note: there are only two lines that mimics the grid, I can draw it later, but for now I want the saved image to not include the grind lines.
You should paint the grid in the paintEvent, instead of continuously painting it onto the image.
def paintEvent(self, event):
painter = QPainter(self)
painter.drawImage(QPoint(), self.image_layer)
gridSize = 10
x = y = 0
width = self.width()
height = self.height()
while y <= height:
# draw horizontal lines
painter.drawLine(0, y, width, y)
y += gridSize
while x <= width:
# draw vertical lines
painter.drawLine(x, 0, x, height)
x += gridSize
What I'm trying to do is when a user (via a touchscreen) clicks on an editable QEditLine I want it to show the Matchbox-Keyboard for user input. When it is not clicked do not show the keyboard.
I've gone through the C documentation, and a few C examples, but I'm lost as too make the jump to Python. I see people mentioning setting the "focus" can someone explain this too me?
import sys
import os
from PyQt5.QtWidgets import QApplication, QFileDialog, QSlider, QComboBox, QCheckBox, QWidget, QMainWindow, QPushButton, QLabel, QGridLayout, QGroupBox, QRadioButton, QMessageBox, QLineEdit
from PyQt5.QtGui import QIcon, QPixmap
from PyQt5.QtCore import pyqtSlot, Qt
class App(QMainWindow):
def __init__(self):
super().__init__()
self.title = 'GUI TESTS'
self.left = 0
self.top = 0
self.width = 800
self.height = 400
self.statusBarMessage = "GUI TEST"
self.currentSprite = 'TEST.png'
self.btn1Active = False
self.btn2Active = False
self.btn3Active = False
self.btn4Active = False
self.btn5Active = False
self.btn6Active = False
self.btn7Active = False
self.btn8Active = False
self.saveLocationDir = ""
self.initUI()
def initUI(self):
self.setWindowTitle(self.title)
self.setGeometry(self.left, self.top, self.width, self.height)
self.statusBar().showMessage(self.statusBarMessage)
self.userNameLabel = QLabel(self)
self.userNameLabel.move(0,125)
self.userNameLabel.setText("What is your name?")
self.userNameLabel.resize(120,20)
self.nameInput = QLineEdit(self)
self.nameInput.move(0,145)
self.nameInput.resize(200,32)
self.nameInput.setEchoMode(0)
#pyqtSlot()
def showKeyboard(self):
command = "matchbox-keyboard"
os.system(command)
It is not recommended to override the events method by assigning a function self.nameInput.mousePressEvent = self.showKeyboard since the tasks of the mousePressEvent of the QLineEdit are lost and could cause unexpected events.
Also, mousePressEvent is not the appropriate event since you can press the QLineEdit many times and it would be called back to the keyboard.
A better option is to launch it in focusInEvent and delete it in focusOutEvent:
import sys
import subprocess
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
class MatchBoxLineEdit(QLineEdit):
def focusInEvent(self, e):
try:
subprocess.Popen(["matchbox-keyboard"])
except FileNotFoundError:
pass
def focusOutEvent(self,e):
subprocess.Popen(["killall","matchbox-keyboard"])
class App(QMainWindow):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
self.setWindowTitle('GUI TESTS')
widget = QWidget()
self.setCentralWidget(widget)
lay = QVBoxLayout(widget)
self.userNameLabel = QLabel("What is your name?")
self.nameInput = MatchBoxLineEdit()
lay.addWidget(self.userNameLabel)
lay.addWidget(self.nameInput)
self.setGeometry(
QStyle.alignedRect(
Qt.LeftToRight,
Qt.AlignCenter,self.sizeHint(),
qApp.desktop().availableGeometry()
)
)
if __name__ == '__main__':
app = QApplication(sys.argv)
w = App()
w.show()
sys.exit(app.exec_())
import sys
import os
from PyQt5.QtWidgets import QApplication, QFileDialog, QSlider, QComboBox, QCheckBox, QWidget, QMainWindow, QPushButton, QLabel, QGridLayout, QGroupBox, QRadioButton, QMessageBox, QLineEdit
from PyQt5.QtGui import QIcon, QPixmap
from PyQt5.QtCore import pyqtSlot, Qt
class App(QMainWindow):
def __init__(self):
super().__init__()
self.title = 'GUI TESTS'
self.left = 0
self.top = 0
self.width = 800
self.height = 400
self.statusBarMessage = "GUI TEST"
self.currentSprite = 'TEST.png'
self.btn1Active = False
self.btn2Active = False
self.btn3Active = False
self.btn4Active = False
self.btn5Active = False
self.btn6Active = False
self.btn7Active = False
self.btn8Active = False
self.saveLocationDir = ""
self.initUI()
def initUI(self):
self.setWindowTitle(self.title)
self.setGeometry(self.left, self.top, self.width, self.height)
self.statusBar().showMessage(self.statusBarMessage)
self.userNameLabel = QLabel(self)
self.userNameLabel.move(0,125)
self.userNameLabel.setText("What is your name?")
self.userNameLabel.resize(120,20)
self.nameInput = QLineEdit(self)
self.nameInput.move(0,145)
self.nameInput.resize(200,32)
self.nameInput.setEchoMode(0)
self.nameInput.mousePressEvent=self.showKeyboard
#pyqtSlot()
def showKeyboard(self,event):
if event.button() == QtCore.Qt.LeftButton:
QtWidgets.QLineEdit.mousePressEvent(self, event)
command = "matchbox-keyboard"
os.system(command)
You can override mousePressEvent and achieve that functionality