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.
Related
(pyqt5 noob here.)
I want to create an overlay that change text location when some conditions are met. I run it under a thread, that I can control from main, as this would be used as an extension of an already existing program. This one would provide coordinates, and the overlay should update the text location based on those.
However, this error is triggered :
A QApplication::exec: Must be called from the main thread is called
I don't get what I'm missing here.
(I've noticed that using X11BypassWindowManagerHint causes some issues, especially with event triggers, but I want the overlay to be transparent, always displayed above the window I'm using, and clickable-through).
Any help, advice or suggestions would be much appreciated !
import sys
from PyQt5.QtWidgets import QApplication, QLabel, QMainWindow, QVBoxLayout, QWidget, QDesktopWidget
from PyQt5.QtGui import QFont
from PyQt5.QtCore import Qt, QCoreApplication, QThread, pyqtSignal, pyqtSlot
from time import sleep
class text_thread(QThread):
position_changed = pyqtSignal(int, int)
def __init__(self, app):
self.app = app
QThread.__init__(self)
def run(self):
self.window = QMainWindow()
self.window.setWindowFlag(Qt.X11BypassWindowManagerHint)
self.window.setWindowFlag(Qt.FramelessWindowHint)
self.window.setWindowFlag(Qt.WindowStaysOnTopHint)
self.window.setAttribute(Qt.WA_TranslucentBackground)
self.window.resize(500, 500)
self.f = QFont("Arial", 30, QFont.Bold)
self.label = QLabel("Text")
self.label.setFont(self.f)
self.label.setGeometry(100, 100, 50, 50)
self.layout = QVBoxLayout()
self.layout.addWidget(self.label)
self.central_widget = QWidget()
self.central_widget.setLayout(self.layout)
self.window.setCentralWidget(self.central_widget)
self.position_changed.connect(self.update_position)
self.window.show()
self.app.exec()
#pyqtSlot(int, int)
def update_position(self, x, y):
self.label.setGeometry(x, y, 50, 50)
app = QApplication(sys.argv)
thread = text_thread(app)
thread.start()
while True:
for i in range(10):
thread.position_changed.emit(100+i*10, 100+i*10)
sleep(1)
I believe that this way you can get a result similar to what you want.
I recommend isolating your test tool.
import sys
from PyQt5.QtWidgets import QApplication, QLabel, QMainWindow, QVBoxLayout, QWidget, QDesktopWidget
from PyQt5.QtGui import QFont
from PyQt5.QtCore import pyqtSignal as Signal, QObject, Qt, QCoreApplication, QThread, pyqtSignal, pyqtSlot
import time
class Tester(QObject):
sig_positions = Signal(int, int)
#pyqtSlot(int)
def action(self, n):
for i in range(1, n+1):
time.sleep(1)
self.sig_positions.emit(100+i*10, 100+i*10)
class Window(QMainWindow):
sig_requested = Signal(int)
def __init__(self):
super().__init__()
self.setWindowFlag(Qt.X11BypassWindowManagerHint)
self.setWindowFlag(Qt.FramelessWindowHint)
self.setWindowFlag(Qt.WindowStaysOnTopHint)
self.setAttribute(Qt.WA_TranslucentBackground)
self.resize(500, 500)
self.f = QFont("Arial", 30, QFont.Bold)
self.label = QLabel("Text")
self.label.setFont(self.f)
self.label.setGeometry(100, 100, 50, 50)
self.layout = QVBoxLayout()
self.layout.addWidget(self.label)
self.central_widget = QWidget()
self.central_widget.setLayout(self.layout)
self.setCentralWidget(self.central_widget)
self.t = Tester()
self.q = QThread()
self.t.sig_positions.connect(self.update_position)
self.sig_requested.connect(self.t.action)
self.t.moveToThread(self.q)
self.q.start()
self.show()
def start_test(self):
print('start')
self.sig_requested.emit(3)
def update_position(self, x, y):
print('update_position')
self.label.setGeometry(x, y, 50, 50)
if __name__ == "__main__":
App = QApplication(sys.argv)
window = Window()
window.start_test()
sys.exit(App.exec())
I am seeing gap into QVBoxLayout when I am placing layout it does not look good, any idea to fix issue
#!/usr/bin/env python
import os
import sys
from PySide2.QtCore import Qt, QSize, QRegExp, QFile, QTextStream
from PySide2.QtGui import QKeySequence, QTextCharFormat, QBrush,QColor, QTextDocument, QTextCursor
from PySide2.QtWidgets import (QApplication, QDesktopWidget, QMainWindow,
QPlainTextEdit, QGridLayout, QGroupBox,
QFormLayout, QHBoxLayout, QLabel, QLineEdit,
QMenu, QMenuBar, QPushButton, QMessageBox,
QTextEdit, QVBoxLayout, QWidget, QAction)
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.width = 1100
self.height = 700
self.set_main_window()
self.create_violation_text()
def set_main_window(self):
"""
Setting main window position
"""
self.setWindowTitle("GUI %s" %(os.path.abspath(__file__)))
self.setFixedSize(QSize(self.width, self.height))
wid = QDesktopWidget()
screen_width = wid.screen().frameGeometry().width()
screen_height = wid.screen().frameGeometry().height()
self.setGeometry(screen_width/2-self.width/2,
screen_height/2-self.height/2,
self.width, self.height)
def create_violation_text(self):
"""
creating main violation window which contain all violations
"""
self.plain_textedit = QPlainTextEdit()
self.plain_textedit.setLineWrapMode(QPlainTextEdit.NoWrap)
self.plain_textedit.setStyleSheet(
"""QPlainTextEdit {font-size: 14pt;
font-family: Courier;}""")
class ReviewWindow(MainWindow):
def __init__(self, waiver_files, app):
"""creating Review mode"""
super().__init__()
self.waiver_files = waiver_files
self.app = app
def create_widget(self):
self.create_text_finder()
self.create_violation_window()
#order matter
main_layout = QVBoxLayout()
main_layout.addWidget(self.text_finder)
main_layout.addWidget(self.create_violation_box)
#creating widgeth object as main window does not
#add layout directly it add only widget
window = QWidget()
window.setLayout(main_layout)
self.setCentralWidget(window)
def create_text_finder(self):
"""
create text finder which wil search string into document
"""
self.text_finder = QGroupBox()
layout = QHBoxLayout()
label = QLabel()
label.setText("Keyword:")
self.line_edit = QLineEdit()
self.line_edit.setText("Enter your search here")
push_button = QPushButton("Find")
push_button.clicked.connect(self.find_string_match)
layout.addWidget(label)
layout.addWidget(self.line_edit)
layout.addWidget(push_button)
self.text_finder.setLayout(layout)
def create_violation_window(self):
"""
creating violation window which contain text editor,
violation type and checkbox
"""
self.create_violation_box = QGroupBox()
layout = QGridLayout()
layout.addWidget(self.plain_textedit, 1, 0, 12, 1)
layout.setColumnMinimumWidth(0, 10)
self.create_violation_box.setLayout(layout)
def find_string_match(self):
"""
Adding string match operation
"""
#format for desire match
format = QTextCharFormat()
format.setBackground(QBrush(QColor("red")))
pattern = QRegExp(self.line_edit.text())
text_document = self.plain_textedit.document()
#Reverting if any
text_document.undo()
if pattern.isEmpty():
QMessageBox.warning("Search filed is empty")
else:
find_cursor = QTextCursor(text_document)
cursor = QTextCursor(text_document)
cursor.beginEditBlock()
while (not find_cursor.isNull() and not find_cursor.atEnd()):
found = False
find_cursor = text_document.find(pattern, find_cursor,
QTextDocument.FindWholeWords)
if (not find_cursor.isNull()):
found = True
find_cursor.movePosition(QTextCursor.WordRight,
QTextCursor.KeepAnchor)
find_cursor.mergeCharFormat(format)
cursor.endEditBlock()
if __name__ == '__main__':
app = QApplication(sys.argv)
cwd = os.path.dirname(__file__)
waiver_file = \[os.path.join(cwd, fdata) for fdata in os.listdir(cwd)\]
window = ReviewWindow(waiver_file, app)
window.create_widget()
window.show()
app.exec_()
I want my window and it's QGraphicsScene to be transparent which is controlled by QSlider.
I tried looking for some answers here and there, but it's mainly setting background color to 0 :
self.setStyleSheet("background-color:rgba(0, 0, 0, 0);")
or like that :
self.setWindowFlags(Qt.FramelessWindowHint)
self.setAttribute(Qt.WA_TranslucentBackground)
Which does it job, but I would like to make slider which will control level of transparency and I don't see how can I do it with commands above.
Can somebody please give me some advise how to do it ? Thank you
I will attach my test code here below(I want to be able to control transparency of everything , but do not touch slider and button):
from PySide2.QtGui import QBrush, QColor
from PySide2.QtCore import QSize, Qt
from PySide2.QtWidgets import QDialog, QVBoxLayout, QGraphicsView, QGraphicsScene, QFrame, QSizePolicy, QApplication, QSlider, QPushButton
class MainWindow(QDialog):
def __init__(self):
QDialog.__init__(self)
self.mainLayout = QVBoxLayout()
self.graphicsWidget = MainGraphicsWidget()
self.window = 'transp_test'
self.title = 'transparent UI'
self.size = (1000, 650)
self.create()
def create(self, **kwargs):
self.setWindowTitle(self.title)
self.resize(QSize(*self.size))
self.setLayout(self.mainLayout)
self.mainLayout.addWidget(self.graphicsWidget)
class MainGraphicsWidget(QGraphicsView):
def __init__(self, parent=None):
super(MainGraphicsWidget, self).__init__(parent)
self._scene = QGraphicsScene(backgroundBrush = Qt.gray)
self.setScene(self._scene)
self.transpSlider = QSlider()
self.transpSlider.setRange(0,100)
self.mainButton = QPushButton('I want it to be "Test" button')
self._scene.addWidget(self.mainButton)
self._scene.addWidget(self.transpSlider)
self.transpSlider.move(300, 100)
self.setTransformationAnchor(QGraphicsView.AnchorUnderMouse)
self.setResizeAnchor(QGraphicsView.AnchorUnderMouse)
self.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
self.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
self.setBackgroundBrush(QBrush(QColor(30, 30, 30)))
self.setFrameShape(QFrame.NoFrame)
self.setSizePolicy(QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding))
if __name__ == '__main__':
import sys
app = QApplication(sys.argv)
window = MainWindow()
window.setGeometry(600, 300, 600, 600)
window.show()
sys.exit(app.exec_())
Here is one way.
class MainWindow(QDialog):
def __init__(self):
QDialog.__init__(self)
# these two lines are needed to get a transparent background in windows
self.setWindowFlags(Qt.FramelessWindowHint)
self.setAttribute(Qt.WA_TranslucentBackground)
# rest of class definition unchanged
class MainGraphicsWidget(QGraphicsView):
def __init__(self, parent=None):
super(MainGraphicsWidget, self).__init__(parent)
# set transparent background color for the widget itself
self.setStyleSheet("background-color: #00000000")
self._scene = QGraphicsScene()
self.setScene(self._scene)
# create of slider and connect to slot for changing opacity.
self.transpSlider = QSlider()
self.transpSlider.setStyleSheet('background-color: #00000000')
self.transpSlider.setRange(0,255)
self.transpSlider.valueChanged.connect(self.set_opacity)
self.transpSlider.setValue(255)
# rest of __init__ unchanged
def set_opacity(self, value):
brush = self.backgroundBrush()
color = brush.color()
color.setAlpha(value)
brush.setColor(color)
self.setBackgroundBrush(color)
Note that I've changed the range of the slider to 0-255 to make changing the opacity from fully opaque to fully transparent easier.
Try it:
#from PySide2.QtGui import QBrush, QColor
#from PySide2.QtCore import QSize, Qt
#from PySide2.QtWidgets import QDialog, QVBoxLayout, QGraphicsView, QGraphicsScene, QFrame, QSizePolicy, QApplication, QSlider, QPushButton
from PyQt5 import QtCore, QtWidgets, QtGui
from PyQt5.QtGui import QBrush, QColor
from PyQt5.QtCore import QSize, Qt
from PyQt5.QtWidgets import (QDialog, QVBoxLayout, QGraphicsView, QGraphicsScene,
QFrame, QSizePolicy, QApplication, QSlider, QPushButton)
class MainGraphicsWidget(QGraphicsView):
def __init__(self, parent=None):
super(MainGraphicsWidget, self).__init__(parent)
self._scene = QGraphicsScene()
self.setScene(self._scene)
self.transpSlider = QtWidgets.QSlider(
QtCore.Qt.Horizontal,
minimum=10,
maximum=100,
value=100,
valueChanged=self.onValueChanged,
)
self.mainButton = QPushButton('I want it to be "Test" button \n QUIT')
self.mainButton.resize(150, 150)
self.mainButton.clicked.connect(parent.close)
self._scene.addWidget(self.mainButton)
self._scene.addWidget(self.transpSlider)
self.transpSlider.move(300, 100)
self.setTransformationAnchor(QGraphicsView.AnchorUnderMouse)
self.setResizeAnchor(QGraphicsView.AnchorUnderMouse)
c = QColor(220, 30, 30)
c.setAlphaF(1)
self.setBackgroundBrush(QBrush(c))
self.setFrameShape(QFrame.NoFrame)
self.setSizePolicy(QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding))
#QtCore.pyqtSlot(int)
def onValueChanged(self, value):
c = QColor(220, 30, 30)
c.setAlphaF(value * 0.01)
self.setBackgroundBrush(QBrush(c))
window.setWindowOpacity(value * 0.03)
self.setStyleSheet("MainGraphicsWidget {{background-color: rgba(0, 215, 55, {});}}".format(value))
class MainWindow(QDialog):
def __init__(self):
super().__init__()
self.setAttribute(Qt.WA_NoSystemBackground, False)
self.setStyleSheet("MainWindow {background-color: rgba(0, 215, 55, 70);}")
self.graphicsWidget = MainGraphicsWidget(self)
self.window = 'transp_test'
self.title = 'transparent UI'
self.size = (1000, 650)
self.setWindowTitle(self.title)
self.resize(QSize(*self.size))
self.mainLayout = QVBoxLayout()
self.setLayout(self.mainLayout)
self.mainLayout.addWidget(self.graphicsWidget)
if __name__ == '__main__':
import sys
app = QApplication(sys.argv)
window = MainWindow()
window.setGeometry(600, 100, 600, 600)
window.show()
sys.exit(app.exec_())
I have a QMainWindow with a toolbar, and I'm having troubles with fitting the QPixmap to the window, such that it won't tackle with the toolbar.
I want to display the picture:
And from the code:
import sys
from PyQt5.QtCore import QRect
from PyQt5.QtWidgets import QAction, QMainWindow, QApplication
from PyQt5.QtGui import QPixmap, QPainter
class Menu(QMainWindow):
def __init__(self):
super().__init__()
newAct = QAction('New', self)
self.toolbar = self.addToolBar('Remove')
self.toolbar.addAction(newAct)
self.image = QPixmap("background.png")
self.setGeometry(100, 30, 500, 300)
self.resize(self.image.width(), self.image.height())
self.show()
def paintEvent(self, event):
painter = QPainter(self)
rect = QRect(0, 0, self.image.width(), self.image.height())
painter.drawPixmap(rect, self.image)
if __name__ == '__main__':
app = QApplication(sys.argv)
mainMenu = Menu()
sys.exit(app.exec_())
I get:
And as you can see, The picture is on the toolbar as well, and I don't want that.
Another try:
import sys
from PyQt5.QtCore import QRect
from PyQt5.QtWidgets import QAction, QMainWindow, QApplication
from PyQt5.QtGui import QPixmap, QPainter
class Menu(QMainWindow):
def __init__(self):
super().__init__()
newAct = QAction('New', self)
self.toolbar = self.addToolBar('Remove')
self.toolbar.addAction(newAct)
self.image = QPixmap("background.png")
self.setGeometry(100, 30, 500, 300)
self.resize(self.image.width(), self.image.height() + self.toolbar.height())
self.show()
def paintEvent(self, event):
painter = QPainter(self)
rect = QRect(0, self.toolbar.height(), self.image.width(), self.image.height() + self.toolbar.height())
painter.drawPixmap(rect, self.image)
if __name__ == '__main__':
app = QApplication(sys.argv)
mainMenu = Menu()
sys.exit(app.exec_())
But I get:
And as you can see, I don't see one of the lines (the blue one).
How can I fix it, so the picture will fit the window excluding the toolbar?
In addition to that, it means I'll have to change all my mouse clicks to move the y-axis. Is there perhaps a way I can set everything such that (x,y)=(0,0) would be at the uppermost left, below the toolbar?
I'm using Python 3.6.5 |Anaconda custom (64-bit) on windows | PyQt version: 5.9.2
Although I can not reproduce the problem, the following solution must work, in it I draw the image in a widget and I set them as centralwidget.
import sys
from PyQt5.QtCore import QRect
from PyQt5.QtWidgets import QAction, QMainWindow, QApplication, QWidget
from PyQt5.QtGui import QPixmap, QPainter
class Widget(QWidget):
def __init__(self, parent=None):
super().__init__(parent)
self.image = QPixmap("background.png")
self.setFixedSize(self.image.size())
def paintEvent(self, event):
painter = QPainter(self)
painter.drawPixmap(self.rect(), self.image)
class Menu(QMainWindow):
def __init__(self):
super().__init__()
newAct = QAction('New', self)
self.toolbar = self.addToolBar('Remove')
self.toolbar.addAction(newAct)
self.setCentralWidget(Widget())
self.setFixedSize(self.sizeHint())
self.show()
if __name__ == '__main__':
app = QApplication(sys.argv)
mainMenu = Menu()
sys.exit(app.exec_())
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