In need a pass a result from an event to QlineEdit box(rs_QLineEdit)
If the event is clicked by passing the Book name it displays book name and price.
There is no problem with database connection as it works well and displays the result in python shell.
I want to pass the price dynamically which is to pass m[2] to rs_QLineEdit
from PyQt5.QtCore import QRegExp
from PyQt5.QtGui import QRegExpValidator
from PyQt5 import QtCore, QtGui, QtWidgets
import sqlite3
def fetch(nm):
store=sqlite3.connect("store.db")
book=store.cursor()
book.execute("select * from books where title='"+nm+"';")
m=book.fetchone()
if m==None:
print("Book is not Found")
else:
print("the name is {} ".format(nm)) #The Wings of Fire
print(m[2]) #200
store.close()
class Ui_Form(object):
def setupUi(self, Form):
Form.setObjectName("Form")
Form.resize(635, 510)
self.find = QtWidgets.QPushButton(Form)
self.find.setGeometry(QtCore.QRect(370, 200, 93, 28))
self.find.setObjectName("find_button")
self.find.setToolTip("Press this")
self.name = QtWidgets.QLabel(Form)
self.name.setGeometry(QtCore.QRect(100, 200, 55, 16))
self.name.setObjectName("name_label")
self.price = QtWidgets.QLabel(Form)
self.price.setGeometry(QtCore.QRect(100, 260, 55, 16))
self.price.setObjectName("price_label")
self.rs = QtWidgets.QLineEdit(Form)
self.rs.setGeometry(QtCore.QRect(230, 260, 55, 16))
self.rs.setObjectName("rs_QLineEdit")
self.lineEdit = QtWidgets.QLineEdit(Form)
self.lineEdit.setGeometry(QtCore.QRect(220, 200, 113, 22))
self.lineEdit.setObjectName("lineEdit")
self.retranslateUi(Form)
QtCore.QMetaObject.connectSlotsByName(Form)
self.find.clicked.connect(lambda : fetch(str(self.lineEdit.text())))
reg_ex = QRegExp("[0-9]+.?[0-9]{,2}")
input_validator = QRegExpValidator(reg_ex, self.rs)
self.rs.setValidator(input_validator)
def retranslateUi(self, Form):
_translate = QtCore.QCoreApplication.translate
Form.setWindowTitle(_translate("Form", "Form"))
self.find.setText(_translate("Form", "Find"))
self.name.setText(_translate("Form", "Name"))
self.price.setText(_translate("Form", "Price"))
self.rs.setText(_translate("Form", "RS."))
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_())
Although lambda methods are useful for certain types of tasks in general you should not abuse them because they have many limitations, in your case the fetch function should return the result but within a lambda method it is difficult to establish (it can be in theory but it would be unreadable).
In addition to this I take the trouble to improve your code following the recommendations of PyQt: http://pyqt.sourceforge.net/Docs/PyQt5/designer.html#using-the-generated-code, in it I recommend not to modify the class generated by Qt Designer but to implement another class that inherits from the widget and use the initial class to fill in the widget, in that new class the logic is implemented.
Code:
import sqlite3
from PyQt5 import QtCore, QtGui, QtWidgets
def fetch(nm):
store=sqlite3.connect("store.db")
book=store.cursor()
book.execute("select * from books where title='{}';".format(nm))
m=book.fetchone()
store.close()
if m:
print("the name is {} ".format(nm))
return m[2]
else:
print("Book is not Found")
class Ui_Form(object):
def setupUi(self, Form):
Form.setObjectName("Form")
Form.resize(635, 510)
self.find = QtWidgets.QPushButton(Form)
self.find.setGeometry(QtCore.QRect(370, 200, 93, 28))
self.find.setObjectName("find_button")
self.find.setToolTip("Press this")
self.name = QtWidgets.QLabel(Form)
self.name.setGeometry(QtCore.QRect(100, 200, 55, 16))
self.name.setObjectName("name_label")
self.price = QtWidgets.QLabel(Form)
self.price.setGeometry(QtCore.QRect(100, 260, 55, 16))
self.price.setObjectName("price_label")
self.rs = QtWidgets.QLineEdit(Form)
self.rs.setGeometry(QtCore.QRect(230, 260, 55, 16))
self.rs.setObjectName("rs_QLineEdit")
self.lineEdit = QtWidgets.QLineEdit(Form)
self.lineEdit.setGeometry(QtCore.QRect(220, 200, 113, 22))
self.lineEdit.setObjectName("lineEdit")
self.retranslateUi(Form)
QtCore.QMetaObject.connectSlotsByName(Form)
def retranslateUi(self, Form):
_translate = QtCore.QCoreApplication.translate
Form.setWindowTitle(_translate("Form", "Form"))
self.find.setText(_translate("Form", "Find"))
self.name.setText(_translate("Form", "Name"))
self.price.setText(_translate("Form", "Price"))
self.rs.setText(_translate("Form", "RS."))
class Widget(QtWidgets.QWidget, Ui_Form):
def __init__(self, parent=None):
QtWidgets.QWidget.__init__(self, parent)
self.setupUi(self)
self.find.clicked.connect(self.onFindClicked)
reg_ex = QtCore.QRegExp("[0-9]+.?[0-9]{,2}")
input_validator = QtGui.QRegExpValidator(reg_ex, self.rs)
self.rs.setValidator(input_validator)
#QtCore.pyqtSlot()
def onFindClicked(self):
title = self.lineEdit.text()
name = fetch(title)
if name:
self.rs.setText(str(name))
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
w = Widget()
w.show()
sys.exit(app.exec_())
The accepted answer is fine, but I don't necessarily agree about avoiding lambda functions. They are super useful when programming in PyQt. As per the docs for QPushButton's super class QAbstractButton, clicked takes one argument, bool checked = false. It's actually pretty useless on QPushButton as far as I've seen, but nevertheless, your lambda has to account for any arguments. Change your connect line to
self.find.clicked.connect(lambda c: fetch(str(self.lineEdit.text())))
# ^ This is the important part
Related
I have a simple pyqt5 script that makes the following UI:
UI
The python file for this code is named 'Test.py' and is as follows:
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_Form(object):
def setupUi(self, Form):
Form.setObjectName("Form")
Form.resize(400, 400)
self.label = QtWidgets.QLabel(Form)
self.label.setGeometry(QtCore.QRect(150, 90, 91, 31))
self.label.setObjectName("label")
self.lineEdit = QtWidgets.QLineEdit(Form)
self.lineEdit.setGeometry(QtCore.QRect(240, 100, 113, 20))
self.lineEdit.setObjectName("lineEdit")
self.pushButton = QtWidgets.QPushButton(Form)
self.pushButton.setGeometry(QtCore.QRect(250, 150, 75, 23))
self.pushButton.setObjectName("pushButton")
self.pushButton.clicked.connect(self.function) #<<<<<<<< MY INPUT
self.retranslateUi(Form)
QtCore.QMetaObject.connectSlotsByName(Form)
def retranslateUi(self, Form):
_translate = QtCore.QCoreApplication.translate
Form.setWindowTitle(_translate("Form", "Form"))
self.label.setText(_translate("Form", "Job Number"))
self.pushButton.setText(_translate("Form", "Press it"))
def function(self): #<<<<<<<< MY INPUT
self.text = self.lineEdit.text() #<<<<<<<< MY INPUT
return self.text #<<<<<<<< MY INPUT
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_())
I simply want to use the 'self.text' value that is generated on a different python file called 'Test1.py'.
I tried tried the following in the 'Test1.py' file:
from Test import Ui_Form
obj = Ui_Form()
obj.function()
But I keep getting the following error:
AttributeError: 'Ui_Form' object has no attribute 'lineEdit'
I am trying to develop a pyqt5 app where I can live stream stock prices from Bloomberg. I put some field names (eg. LAST_TRADE) in the ThreadClass (QThread) to pull price every second. I also have a function in the main class to pull some non-realtime data (eg. PX_YEST_CLOSE) from Bloomberg whenever a push button is clicked. I ran into this issue that when the push button clicked, it sometimes returns LAST_TRADE data instead of PX_YEST_CLOSE. I think this is because the API only allow one request at a time. Is there a better way to workaround it?
I've included a simple version of my code below just to illustrate. Thank you!
import sys, time
from xbbg import blp
from PyQt5 import QtCore, QtWidgets
from PyQt5.QtWidgets import QMainWindow
from ui_interface import Ui_MainWindow
ticker = ['AMD Equity', 'NVDA Equity', 'CHK Equity', 'ABNB Equity', 'AFRM Equity', 'U Equity']
live_fields = ['LAST_TRADE']
class MainWindow(QMainWindow, Ui_MainWindow):
"""Class for the Main window"""
def __init__(self, parent=None):
super().__init__(parent)
self.setupUi(self)
self.thread={}
self.getStaticData()
self.connectSignalsSlots()
self.start_worker()
def getStaticData(self):
'''Pull static data from Bloomberg'''
self.staticData = blp.bdp(list(set(ticker)), flds=['CUR_MKT_CAP', 'PX_YEST_CLOSE'])
self.label_2.setText(str(self.staticData.iat[0,0]))
def start_worker(self):
self.thread[1] = ThreadClass(parent = None)
self.thread[1].start()
self.thread[1].any_signal.connect(self.liveFeed)
def liveFeed(self,liveData):
self.label.setText(str(liveData.iat[0,0]))
def updateData(self):
'''Update table if clicked'''
print(blp.bdp(['AAPL Equity'], flds=['CUR_MKT_CAP', 'PX_YEST_CLOSE']))
def connectSignalsSlots(self):
'''Signal-slots connections'''
self.pushButton.clicked.connect(self.updateData)
class ThreadClass(QtCore.QThread):
any_signal = QtCore.pyqtSignal(object)
def __init__(self, parent=None):
super(ThreadClass, self).__init__(parent)
self.is_running = True
def run(self):
print('Starting...')
while (True):
data=blp.bdp(ticker, flds=live_fields)
time.sleep(0.1)
self.any_signal.emit(data)
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
control = MainWindow()
widget = QtWidgets.QStackedWidget()
widget.addWidget(control)
widget.show()
sys.exit(app.exec())
UI below:
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
if not MainWindow.objectName():
MainWindow.setObjectName(u"MainWindow")
MainWindow.resize(590, 582)
self.centralwidget = QWidget(MainWindow)
self.centralwidget.setObjectName(u"centralwidget")
self.pushButton = QPushButton(self.centralwidget)
self.pushButton.setObjectName(u"pushButton")
self.pushButton.setGeometry(QRect(360, 80, 75, 23))
self.label = QLabel(self.centralwidget)
self.label.setObjectName(u"label")
self.label.setGeometry(QRect(90, 70, 171, 41))
self.label_2 = QLabel(self.centralwidget)
self.label_2.setObjectName(u"label_2")
self.label_2.setGeometry(QRect(90, 140, 171, 41))
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QMenuBar(MainWindow)
self.menubar.setObjectName(u"menubar")
self.menubar.setGeometry(QRect(0, 0, 590, 21))
MainWindow.setMenuBar(self.menubar)
self.statusbar = QStatusBar(MainWindow)
self.statusbar.setObjectName(u"statusbar")
MainWindow.setStatusBar(self.statusbar)
self.retranslateUi(MainWindow)
QMetaObject.connectSlotsByName(MainWindow)
# setupUi
def retranslateUi(self, MainWindow):
MainWindow.setWindowTitle(QCoreApplication.translate("MainWindow", u"MainWindow", None))
self.pushButton.setText(QCoreApplication.translate("MainWindow", u"Update", None))
self.label.setText(QCoreApplication.translate("MainWindow", u"TextLabel", None))
self.label_2.setText(QCoreApplication.translate("MainWindow", u"TextLabel", None))
How to fetch the data from Qcalendar. For example, when is select 21/10/2019, "Monday" will be fetched when I click the "ok" button
The following is my code:
from PyQt5 import QtCore, QtWidgets
from PyQt5.QtWidgets import QMainWindow, QVBoxLayout, QCalendarWidget
class Ui_Form(QMainWindow):
def __init__(self):
self.calendarWidget = QtWidgets.QCalendarWidget(Form)
self.label = QtWidgets.QLabel(Form)
self.pushButton = QtWidgets.QPushButton(Form)
self.pushButton_2 = QtWidgets.QPushButton(Form)
def setupUi(self, Form):
Form.setObjectName("Form")
Form.resize(700, 700)
self.calendarWidget.setGeometry(QtCore.QRect(100, 110, 510, 454))
self.calendarWidget.setMinimumSize(QtCore.QSize(200, 144))
self.calendarWidget.setObjectName("calendarWidget")
self.label.setGeometry(QtCore.QRect(100, 50, 101, 31))
self.label.setObjectName("label")
self.pushButton.setGeometry(QtCore.QRect(460, 600, 76, 37))
self.pushButton.setObjectName("backButton")
self.pushButton_2.setGeometry(QtCore.QRect(560, 600, 76, 37))
self.pushButton_2.setObjectName("okbutton")
self.retranslateUi(Form)
QtCore.QMetaObject.connectSlotsByName(Form)
selectionMode()
def retranslateUi(self, Form):
_translate = QtCore.QCoreApplication.translate
Form.setWindowTitle(_translate("Form", "Select date"))
self.label.setText(_translate("Form", "Select date"))
self.pushButton.setText(_translate("Form", "Back"))
self.pushButton_2.setText(_translate("Form", "ok"))
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_())
void QCalendarWidget::clicked(const QDate &date)
This signal is emitted when a mouse button is clicked.
The date the mouse was clicked on is specified by date.
The signal is only emitted when clicked on a valid date, e.g.,
dates are not outside the minimumDate() and maximumDate().
If the selection mode is NoSelection, this signal will not be emitted.
QString QDate::toString(const QString &format) const
Returns the date as a string. The format parameter determines the format of the result string.
https://doc.qt.io/qt-5/qdate.html#toString-2
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import QMainWindow, QVBoxLayout, QCalendarWidget, QWidget
# WARNING! All changes made in this file will be lost!
class Ui_Form(object):
'''
# WARNING! All changes made in this file will be lost !!!!!!
class Ui_Form(QMainWindow):
def __init__(self):
self.calendarWidget = QtWidgets.QCalendarWidget(Form)
self.label = QtWidgets.QLabel(Form)
self.pushButton = QtWidgets.QPushButton(Form)
self.pushButton_2 = QtWidgets.QPushButton(Form)
'''
def setupUi(self, Form):
Form.setObjectName("Form")
Form.resize(700, 700)
self.calendarWidget = QtWidgets.QCalendarWidget(Form)
self.calendarWidget.setGeometry(QtCore.QRect(100, 110, 510, 454))
self.calendarWidget.setMinimumSize(QtCore.QSize(200, 144))
self.calendarWidget.setObjectName("calendarWidget")
self.label = QtWidgets.QLabel(Form)
self.label.setGeometry(QtCore.QRect(100, 50, 101, 31))
self.label.setObjectName("label")
self.pushButton = QtWidgets.QPushButton(Form)
self.pushButton.setGeometry(QtCore.QRect(460, 600, 76, 37))
self.pushButton.setObjectName("backButton")
self.pushButton_2 = QtWidgets.QPushButton(Form)
self.pushButton_2.setGeometry(QtCore.QRect(560, 600, 76, 37))
self.pushButton_2.setObjectName("okbutton")
self.retranslateUi(Form)
QtCore.QMetaObject.connectSlotsByName(Form)
# ? selectionMode()
def retranslateUi(self, Form):
_translate = QtCore.QCoreApplication.translate
Form.setWindowTitle(_translate("Form", "Select date"))
self.label.setText(_translate("Form", "Select date"))
self.pushButton.setText(_translate("Form", "Back"))
self.pushButton_2.setText(_translate("Form", "ok"))
class MyWindow(QtWidgets.QWidget, Ui_Form):
def __init__(self):
super(MyWindow, self).__init__()
self.setupUi(self)
self.calendarWidget.setGridVisible(True)
self.calendarWidget.clicked[QtCore.QDate].connect(self.showDate)
self.date = self.calendarWidget.selectedDate()
self.label.setText(self.date.toString("dd-MM-yyyy dddd"))
self.pushButton_2.clicked.connect(self.clickedOk)
def showDate(self, date):
# self.label.setText(date.toString("dd-MM-yyyy dddd")) # ! Try to uncomment !
self.date = date
def clickedOk(self):
self.label.setText(self.date.toString("dd-MM-yyyy dddd"))
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
# Form = QtWidgets.QWidget()
# ui = Ui_Form()
# ui.setupUi(Form)
# Form.show()
w = MyWindow()
w.show()
sys.exit(app.exec_())
This question already has an answer here:
Get text from qtextedit and assign it to a variable
(1 answer)
Closed 4 years ago.
whenever I click a button in the second window of my PyQt5 application that should just print the value of a QDateEdit in the GUI, it closes with the line: "Process finished with exit code -1073740791 (0xC0000409)". I figured out that the problem has something to do with the .value() method. Here's the Minimal to reproduce the bug with the Ui_Form class below:
import sys
from PyQt5 import QtWidgets
from ui.fenster import Ui_Form
app = QtWidgets.QApplication(sys.argv)
class AppendWindow(QtWidgets.QMainWindow):
def __init__(self, parent=None):
super().__init__(parent)
self.ui = Ui_Form()
self.ui.setupUi(self)
self.ui.submit.clicked.connect(self.show_value)
def show_value(self):
print(self.ui.date.value())
append = AppendWindow()
append.show()
sys.exit(app.exec_())
Ui_Form:
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_Form(object):
def setupUi(self, Form):
Form.setObjectName("Form")
Form.resize(413, 215)
self.date = QtWidgets.QDateEdit(Form)
self.date.setGeometry(QtCore.QRect(72, 26, 321, 20))
self.date.setObjectName("date")
self.label = QtWidgets.QLabel(Form)
self.label.setGeometry(QtCore.QRect(9, 26, 57, 16))
self.label.setObjectName("label")
self.age = QtWidgets.QSpinBox(Form)
self.age.setGeometry(QtCore.QRect(70, 120, 321, 20))
self.age.setObjectName("age")
self.label_2 = QtWidgets.QLabel(Form)
self.label_2.setGeometry(QtCore.QRect(10, 120, 23, 16))
self.label_2.setObjectName("label_2")
self.label_3 = QtWidgets.QLabel(Form)
self.label_3.setGeometry(QtCore.QRect(9, 69, 27, 16))
self.label_3.setObjectName("label_3")
self.name = QtWidgets.QPlainTextEdit(Form)
self.name.setGeometry(QtCore.QRect(72, 69, 319, 21))
self.name.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
self.name.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
self.name.setObjectName("name")
self.submit = QtWidgets.QPushButton(Form)
self.submit.setGeometry(QtCore.QRect(170, 170, 75, 23))
self.submit.setObjectName("submit")
self.retranslateUi(Form)
QtCore.QMetaObject.connectSlotsByName(Form)
def retranslateUi(self, Form):
_translate = QtCore.QCoreApplication.translate
Form.setWindowTitle(_translate("Form", "Form"))
self.label.setText(_translate("Form", "Geburtsjahr"))
self.label_2.setText(_translate("Form", "Alter"))
self.label_3.setText(_translate("Form", "Name"))
self.submit.setText(_translate("Form", "Absenden!"))
Does anyone know how to fix this?
I appreciate your help!
You need to add app.exec() in your main code in order to start the main loop.
app = QtWidgets.QApplication(sys.argv)
app.exec()
The main loop handles all the incoming events and passes them to your GUI elements.
I've just started doing Qt designing using python 3.x in Pycharms. I've watched a tuturial converting a .ui file to .py file. I'm good right now. I'm implementing a chat program.
Now, I want to type in TextEdit, linEdit but it dosen't wait for me type. I want to connect a keyboard or mouse event with them so when i click, it wait for me to type and when I hit Enter it stores the string.
The code between space and #here that's where I need help with. Basically I want to def methods for these events and calling them from them later.
My Ui_MainWindow class is as follows:
class Ui_MainWindow(QtGui.QMainWindow):
def __init__(self):
super(Ui_MainWindow,self).__init__()
self.setObjectName(_fromUtf8("MainWindow"))
self.resize(611, 487)
self.setTabShape(QtGui.QTabWidget.Rounded)
self.centralwidget = QtGui.QWidget(self)
self.centralwidget.setObjectName(_fromUtf8("centralwidget"))
self.frame = QtGui.QFrame(self.centralwidget)
self.frame.setGeometry(QtCore.QRect(10, 30, 591, 41))
self.frame.setFrameShape(QtGui.QFrame.StyledPanel)
self.frame.setFrameShadow(QtGui.QFrame.Raised)
self.frame.setObjectName(_fromUtf8("frame"))
self.label = QtGui.QLabel(self.frame)
self.label.setGeometry(QtCore.QRect(10, 10, 81, 17))
self.label.setObjectName(_fromUtf8("label"))
self.label_2 = QtGui.QLabel(self.frame)
self.label_2.setGeometry(QtCore.QRect(320, 10, 66, 17))
self.label_2.setObjectName(_fromUtf8("label_2"))
#Here
self.lineEdit = QtGui.QLineEdit(self.frame)
self.lineEdit.setGeometry(QtCore.QRect(90, 10, 221, 21))
self.lineEdit.setObjectName(_fromUtf8("lineEdit"))
#Here
self.lineEdit_3 = QtGui.QLineEdit(self.frame)
self.lineEdit_3.setGeometry(QtCore.QRect(360, 10, 221, 21))
self.lineEdit_3.setObjectName(_fromUtf8("lineEdit_3"))
self.frame_2 = QtGui.QFrame(self.centralwidget)
self.frame_2.setGeometry(QtCore.QRect(10, 70, 291, 361))
self.frame_2.setFrameShape(QtGui.QFrame.StyledPanel)
self.frame_2.setFrameShadow(QtGui.QFrame.Raised)
self.frame_2.setObjectName(_fromUtf8("frame_2"))
#Here
self.textEdit = QtGui.QTextEdit(self.frame_2)
self.textEdit.setGeometry(QtCore.QRect(10, 10, 271, 301))
self.textEdit.setObjectName(_fromUtf8("textEdit"))
self.pushButton_3 = QtGui.QPushButton(self.frame_2)
self.pushButton_3.setGeometry(QtCore.QRect(10, 310, 161, 41))
self.pushButton_3.setObjectName(_fromUtf8("pushButton_3"))
self.pushButton_4 = QtGui.QPushButton(self.frame_2)
self.pushButton_4.setGeometry(QtCore.QRect(180, 310, 98, 41))
self.pushButton_4.setObjectName(_fromUtf8("pushButton_4"))
self.pushButton_4.clicked.connect(self.clrLogs) # Clear Logs from WidgetList by clicking
self.verticalScrollBar = QtGui.QScrollBar(self.frame_2)
self.verticalScrollBar.setGeometry(QtCore.QRect(260, 10, 20, 301))
self.verticalScrollBar.setMinimumSize(QtCore.QSize(16, 301))
self.verticalScrollBar.setCursor(QtGui.QCursor(QtCore.Qt.SizeVerCursor))
self.verticalScrollBar.setAutoFillBackground(False)
self.verticalScrollBar.setOrientation(QtCore.Qt.Vertical)
self.verticalScrollBar.setInvertedAppearance(False)
self.verticalScrollBar.setObjectName(_fromUtf8("verticalScrollBar"))
######################################################
# Scroll to the bottom of chat windows
# self.textEdit.verticalScrollBar().setValue(self.textEdit.verticalScrollBar().maximum)
self.frame_3 = QtGui.QFrame(self.centralwidget)
self.frame_3.setGeometry(QtCore.QRect(300, 70, 301, 361))
self.frame_3.setFrameShape(QtGui.QFrame.StyledPanel)
self.frame_3.setFrameShadow(QtGui.QFrame.Raised)
self.frame_3.setObjectName(_fromUtf8("frame_3"))
self.listWidget = QtGui.QListWidget(self.frame_3)
self.listWidget.setGeometry(QtCore.QRect(10, 10, 281, 341))
self.listWidget.setObjectName(_fromUtf8("listWidget"))
self.verticalScrollBar_2 = QtGui.QScrollBar(self.frame_3)
self.verticalScrollBar_2.setGeometry(QtCore.QRect(270, 10, 21, 341))
self.verticalScrollBar_2.setOrientation(QtCore.Qt.Vertical)
self.verticalScrollBar_2.setObjectName(_fromUtf8("verticalScrollBar_2"))
self.setCentralWidget(self.centralwidget)
self.menubar = QtGui.QMenuBar(self)
self.menubar.setGeometry(QtCore.QRect(0, 0, 611, 25))
self.menubar.setObjectName(_fromUtf8("menubar"))
self.menuMenu_Actions = QtGui.QMenu(self.menubar)
self.menuMenu_Actions.setObjectName(_fromUtf8("menuMenu_Actions"))
self.setMenuBar(self.menubar)
self.statusbar = QtGui.QStatusBar(self)
self.statusbar.setObjectName(_fromUtf8("statusbar"))
self.setStatusBar(self.statusbar)
self.actionVersion = QtGui.QAction(self)
self.actionVersion.setObjectName(_fromUtf8("actionVersion"))
self.actionVersion.triggered.connect(Chat.app_ver) # When submenu Action item Version is clicked
self.actionExit = QtGui.QAction(self)
self.actionExit.setObjectName(_fromUtf8("actionExit"))
self.actionExit.triggered.connect(qApp.quit) #When submenu Action item Exit is clicked
self.menuMenu_Actions.addAction(self.actionVersion)
self.menuMenu_Actions.addAction(self.actionExit)
self.menubar.addAction(self.menuMenu_Actions.menuAction())
self.retranslateUi(self)
QtCore.QMetaObject.connectSlotsByName(self)
def retranslateUi(self, MainWindow):
MainWindow.setWindowTitle(_translate("MainWindow", WindowTitle, None))
self.setWindowIcon(QtGui.QIcon('chat_icon'))
self.label.setText(_translate("MainWindow", "IP Address:", None))
self.label_2.setText(_translate("MainWindow", "Nick:", None))
self.pushButton_3.setText(_translate("MainWindow", "Send SMS", None))
self.pushButton_4.setText(_translate("MainWindow", "Clear Logs", None))
self.menuMenu_Actions.setTitle(_translate("MainWindow", "Menu Actions", None))
self.actionVersion.setText(_translate("MainWindow", "Version", None))
self.actionExit.setText(_translate("MainWindow", "Exit", None))
def clrLogs(self):
self.listWidget.clear()
The big left is TextEdit and rightmost is listWidget. I want to type in TextEdit and stores it and and send this msg to Chatlog(ListWidget).
I would start saying that you have to care about the following things:
Your keyboard UI, let's say a small prototype.
Be aware of who is getting your keyboard focus.
Take care of your filter to catch the events you need.
Send the right response to the claimant object from your keyboard.
I'd show your here some really nice example I've spent some considerable time to do and another one really simple and small. Since it's a quite amount of code I'd be leaving this small example and this more complex example from my github.
You can clone or copy and paste the code, just be sure it comes with the right imports if you copy and paste.
Edited[Added]
Here is the small example catching the events from the receiver you pass, and posting the equivalent events:
import sys
from PyQt5.QtCore import QCoreApplication
from PyQt5.QtCore import QEvent
from PyQt5.QtCore import Qt
from PyQt5.QtCore import pyqtSignal
from PyQt5.QtGui import QKeyEvent
from PyQt5.QtWidgets import QApplication
from PyQt5.QtWidgets import QHBoxLayout
from PyQt5.QtWidgets import QLineEdit
from PyQt5.QtWidgets import QMainWindow
from PyQt5.QtWidgets import QPushButton
from PyQt5.QtWidgets import QWidget
class MainWindow(QMainWindow):
def __init__(self):
super(MainWindow, self).__init__()
self.central_widget = QWidget()
self.cw_layout = QHBoxLayout()
self.central_widget.setLayout(self.cw_layout)
self.setCentralWidget(self.central_widget)
self.line = LineEdit()
self.kb = KeyBoard(self.line)
self.cw_layout.addWidget(self.line)
self.create_connections()
def create_connections(self):
self.line.signal_evoke_kb.connect(self.show_kb)
def show_kb(self):
if self.kb.isHidden():
self.kb.show()
else:
self.kb.hide()
class LineEdit(QLineEdit):
signal_evoke_kb = pyqtSignal()
def __init__(self):
super(LineEdit, self).__init__()
def mousePressEvent(self, QMouseEvent):
super(LineEdit, self).mousePressEvent(QMouseEvent)
self.signal_evoke_kb.emit()
class Key(QPushButton):
def __init__(self, name, event, receiver):
super(Key, self).__init__()
self.name = name
self.event = event
self.setText(name)
class KeyBoard(QWidget):
def __init__(self, receiver):
super(KeyBoard, self).__init__()
self.receiver = receiver
self.layout = QHBoxLayout()
self.keys = ['q','w','e','r','t','y']
self.dict_keys ={'q':Qt.Key_Q,'w':Qt.Key_W,'e':Qt.Key_E,'r':Qt.Key_R,'t':Qt.Key_T,'y':Qt.Key_Y,}
for key in self.keys:
key_keyboard = Key(key,self.dict_keys[key],receiver)
key_keyboard.clicked.connect(self.key_pressed)
self.layout.addWidget(key_keyboard)
self.setLayout(self.layout)
def key_pressed(self):
try:
event = QKeyEvent(QEvent.KeyPress, self.sender().event, Qt.NoModifier,
self.sender().name, False)
QCoreApplication.postEvent(self.receiver, event)
except Exception as e:
print(e)
def keyPressEvent(self, evt):
event = QKeyEvent(QEvent.KeyPress, evt.key(), evt.modifiers(),
evt.text(), False)
QCoreApplication.postEvent(self.receiver, event)
evt.ignore()
if __name__ == "__main__":
app = QApplication(sys.argv)
mw = MainWindow()
mw.show()
sys.exit(app.exec_())
In this way you can personalize your key since your have your own Key, and organize it better when you need upper case and all else. If you are willing to do that I'd strongly recommend looking at the more complete example I linked before.