I am migrating some code from pyGObject to pyQT4 and I make use of set_progress_fraction as a means to indication the percentage of the MAXIMUM the inputted value is.
I am trying to find an equivalent in pyQT4 but I am failing.
QLineEdit does have a paint method so is the only real way to "paint" the LineEdit?
--edit--
example of the gtk equiv:
& snippit of my present pyGObject code
def on_entry_change(self,widget,*args):
try:
tmp = float(widget.get_text())
tmp = (tmp- widget.min_bin)/(widget.max_bin - widget.min_bin)
widget.set_progress_fraction(tmp)
except:
return
I think you want to connect the value in the QLineEdit to a method that modifies the progress bar. This might help:
from __future__ import division
import sys
from PyQt4.QtCore import (Qt, SIGNAL)
from PyQt4.QtGui import (QApplication, QDialog, QLineEdit,
QVBoxLayout, QProgressBar, QWidget, QLabel)
class Form(QWidget):
def __init__(self, parent=None):
super(Form, self).__init__(parent)
self.barA = QProgressBar()
self.maximum = 200
self.label1 = QLabel('Maximum = 200')
self.seqM = QLineEdit("num")
layoutO = QVBoxLayout() #set overal layout
layoutO.addWidget(self.label1)
layoutO.addWidget(self.barA)
layoutO.addWidget(self.seqM)
self.setLayout(layoutO)
self.connect(self.seqM, SIGNAL("returnPressed()"), self.updatebar)
def updatebar(self):
try:
currval = float(self.seqM.text())
except:
print 'enter float or integer only'
self.track = (currval/self.maximum)*100
self.barA.setValue(self.track)
app = QApplication(sys.argv)
form = Form()
form.show()
app.exec_()`
Related
I am studing python and making bookmark function for practice purpose.
Now I could register url to tab menu.
and when I press the link from tab menu. nothing shows on browser.
following area, somebody please le me know what is wrong.
"self.browser.setUrl(QUrl(action_url))"
text itself(action_url) looks OK, but browser does not show.
entire code is this.
import os
import sys
from PyQt5.QtCore import QSize, Qt, QUrl
from PyQt5.QtGui import QIcon, QPixmap
from PyQt5.QtWebEngineWidgets import QWebEngineView
from PyQt5.QtWidgets import (
QAction,
QApplication,
QDialog,
QDialogButtonBox,
QFileDialog,
QLabel,
QLineEdit,
QMainWindow,
QToolBar,
QVBoxLayout,
)
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.browser = QWebEngineView()
self.browser.setUrl(QUrl("http://google.com"))
self.setCentralWidget(self.browser)
# tag::navigation1[]
navtb = QToolBar("Navigation")
navtb.setIconSize(QSize(16, 16))
self.addToolBar(navtb)
#bookmark button
bookmark_btn = QAction(QIcon(os.path.join("icons", "smiley.png")), "Bookmark", self)
bookmark_btn.setStatusTip("add to bookmark")
bookmark_btn.triggered.connect(self.add_bookmark)
navtb.addAction(bookmark_btn)
navtb.addSeparator()
# tag::menuBookmark[]
self.bookmark_menu = self.menuBar().addMenu("&Bookmark")
bookmark_select_action = QAction("http://google.com",self)
bookmark_select_action.triggered.connect(self.navigate_bookmark)
self.bookmark_menu.addAction(bookmark_select_action)
self.show()
# tag::bookmark[]
def add_bookmark(self):
bookmark_title = self.browser.page().title()
bookmark_url = self.browser.url().toString()
bookmark_select_action = QAction(bookmark_url,self)
bookmark_select_action.triggered.connect(self.navigate_bookmark)
self.bookmark_menu.addAction(bookmark_select_action)
# tag::navigationBookmark[]
def navigate_bookmark(self):
action = self.sender()
action_url = '"'+action.text()+'"'
self.browser.setUrl(QUrl(action_url)) #this code does not function as I expected
print(action_url)
app = QApplication(sys.argv)
app.setApplicationName("Mozzarella Ashbadger")
app.setOrganizationName("Mozzarella")
app.setOrganizationDomain("mozzarella.org")
window = MainWindow()
app.exec_()
I don't understand why you put the text inside the quotation marks. In general if you have a string and you want to convert it to QUrl use QUrl::fromUserInput(), also use the load() method:
def navigate_bookmark(self):
action = self.sender()
url = QUrl.fromUserInput(action.text())
self.browser.load(url)
Another strategy is to save the QUrl in the QAction and then retrieve it:
def add_bookmark(self):
bookmark_title = self.browser.page().title()
bookmark_url = self.browser.url()
bookmark_select_action = QAction(bookmark_url.toString(), self)
bookmark_select_action.setData(bookmark_url)
# or
# bookmark_select_action.setProperty("url", bookmark_url)
bookmark_select_action.triggered.connect(self.navigate_bookmark)
self.bookmark_menu.addAction(bookmark_select_action)
def navigate_bookmark(self):
action = self.sender()
url = action.data()
# or
# url = action.property("url")
self.browser.load(url)
I want the "Add" function to run when I input a number into "LE1" and press the "Enter" key on the keyboard. I also want the line edit to clear its text when I select it for editing.
from PyQt5 import QtWidgets, QtCore
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QLineEdit, QLabel, QGridLayout, QWidget, QDialog
class MyWindow(QtWidgets.QMainWindow):
def __init__(self):
super(MyWindow, self).__init__()
centralWidget = QWidget()
self.setCentralWidget(centralWidget)
self.Glayout = QGridLayout(centralWidget)
self.LE1 = QLineEdit('Input Number',self)
self.LE1.keyPressEvent(self.KPE)
Label1 = QLabel('+ 1 =',self)
self.LE2 = QLineEdit(self)
self.Glayout.addWidget(self.LE1)
self.Glayout.addWidget(Label1)
self.Glayout.addWidget(self.LE2)
def Add(self):
Num = float(self.LE1.text())
math = Num + 1
ans = str(math)
self.LE2.setText(ans)
def KPE(self):
if event.key() == Qt.Key_Enter:
self.Add()
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
window = MyWindow()
window.show()
sys.exit(app.exec_())
keyPressEvent is a method that if you override it that way you are losing the default behavior, besides it is unnecessary since QLineEdit has the returnPressed signal that notifies if Enter is pressed.
On the other hand, converting a string to floating can throw an exception so you should prevent that case, another better option is to use a widget that allows only numerical values with QSpinBox or QDoubleSpinBox, or at least restrict the values that are entered into the QLineEdit with a QValidator appropriate.
And finally do not use the word math as a variable name since that is the name of a library that could cause you problems in the future.
Considering the above, the solution is:
from PyQt5.QtWidgets import (
QApplication,
QGridLayout,
QLineEdit,
QLabel,
QMainWindow,
QWidget,
)
class MyWindow(QMainWindow):
def __init__(self, parent=None):
super(MyWindow, self).__init__(parent)
self.LE1 = QLineEdit("Input Number")
self.LE1.returnPressed.connect(self.add)
Label1 = QLabel("+ 1 =")
self.LE2 = QLineEdit()
centralWidget = QWidget()
self.setCentralWidget(centralWidget)
layout = QGridLayout(centralWidget)
layout.addWidget(self.LE1)
layout.addWidget(Label1)
layout.addWidget(self.LE2)
def add(self):
try:
num = float(self.LE1.text())
num += 1
self.LE2.setText(str(num))
except ValueError:
pass
if __name__ == "__main__":
import sys
app = QApplication(sys.argv)
window = MyWindow()
window.show()
sys.exit(app.exec_())
Hello python community
I'm trying to apply a QStandardItemModel on a QTableView according to the text from QLineEdid, of course i've found documentation and it works great on latins letters, but in may case, data is arabic.
let d be a data from my table, and t the text from editline, i have to apply a function on both d and t before comparing them with RegExp (a function from PyArabic) and I don't know how to do that.
I hope to find help here
Thank you!!
here is my code
import sys
from PyQt5.QtCore import Qt, QSortFilterProxyModel, QRegExp
from PyQt5.QtGui import QStandardItemModel, QStandardItem
from PyQt5.QtWidgets import QWidget, QLineEdit, QTableView, QVBoxLayout, QApplication
from pyarabic.araby import strip_tashkeel
class MyWindow(QWidget):
def __init__(self):
super(QWidget, self).__init__()
word_edit = QLineEdit()
word_edit.setLayoutDirection(Qt.RightToLeft)
word_edit.textChanged.connect(self.word_edit_text_changed)
model = QStandardItemModel()
model.setHorizontalHeaderLabels(['الكلمة', 'الطبيعة', 'الحالة'])
model.appendRow([QStandardItem('ذَهبَ'), QStandardItem('فعل'), QStandardItem('غير مراقب')])
model.appendRow([QStandardItem('ذُهبٌ'), QStandardItem('اسم'), QStandardItem('مراقب')])
model.appendRow([QStandardItem('مَذهب'), QStandardItem('اسم'), QStandardItem('مراقب')])
self.filter = QSortFilterProxyModel()
self.filter.setSourceModel(model)
self.filter.setFilterKeyColumn(0)
words_table = QTableView()
words_table.setLayoutDirection(Qt.RightToLeft)
words_table.setModel(self.filter)
v_layout = QVBoxLayout()
v_layout.addWidget(word_edit)
v_layout.addWidget(words_table)
self.setLayout(v_layout)
def word_edit_text_changed(self, text):
# let d be an the date from the model
# i need to compare strip_tashkeel(text) to strip_tashkeel(d)
search = QRegExp(strip_tashkeel(text), Qt.CaseInsensitive)
self.filter.setFilterRegExp(search)
if __name__ == '__main__':
app = QApplication(sys.argv)
w = MyWindow()
w.show()
sys.exit(app.exec_())
I have design a customized formlayout ui using pyqt5 and want to import variables back to the main function for further execution of the main function.
I have tried many ways to get the return values from the main function when the "OK" button has clicked but unable to get the variables from the main function.
Can you please guide me, how can i get the variables from the pyqt5 formlayout ui to main function -
Here is the Code of PyQt5 FormLayout UI function -
from PyQt5.QtWidgets import (QApplication, QComboBox, QDialog,
QDialogButtonBox, QFormLayout, QGridLayout, QGroupBox, QHBoxLayout,
QLabel, QLineEdit, QMenu, QMenuBar, QPushButton, QSpinBox, QTextEdit,
QVBoxLayout,QCheckBox)
import sys
app = QApplication([])
class Dialog(QDialog):
def __init__(self,dinput):
super(Dialog, self).__init__()
self.createFormGroupBox(dinput)
buttonBox = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
buttonBox.accepted.connect(self.accept)
buttonBox.rejected.connect(self.reject)
mainLayout = QVBoxLayout()
mainLayout.addWidget(self.formGroupBox)
mainLayout.addWidget(buttonBox)
self.setLayout(mainLayout)
self.setWindowTitle("Form Layout")
def accept(self):
print(self.linedit1.text())
print(self.combox1.currentText())
print(self.spinbox1.value())
self.closeEvent()
def reject(self):
print('Cancelled')
self.closeEvent()
def getoutput(self):
return self.linedit1.text()
def createFormGroupBox(self,dinput):
self.formGroupBox = QGroupBox("Form layout")
layout = QFormLayout()
self.linedit1 = QLineEdit()
self.linedit1.setText('TestName')
layout.addRow(QLabel(dinput[0]), self.linedit1)
self.combox1 = QComboBox()
self.combox1.setToolTip('Hello')
self.combox1.addItems(['India','France','UK','USA','Germany'])
layout.addRow(QLabel(dinput[1]), self.combox1)
self.spinbox1 = QSpinBox()
layout.addRow(QLabel(dinput[2]), self.spinbox1)
self.formGroupBox.setLayout(layout)
Main Function is -
import os
import sys
import pyformlayout as pyfl
# Staring Functions for Execution
dinput = ['LastName','Country','Age']
# Call the UI and get the inputs
dialog = pyfl.Dialog(dinput)
if(dialog.exec_()):
TName = dialog.getoutput
print('------------------')
print(TName)
# Main Function Continous by getting the inputs
# from UI
I am unable to get the desired values to the output function. Even i have used the getoutput function to return the values and get the output to "TName". But i am not able to get the value into the TName variable and nothing is displaying.
The Result i am getting is - (which is basically printing the accept button function but not the TName variable which is returned to Main function.
TestName
India
25
How can i get the return values from PyQt5 Formlayout UI function to Main function..?
In the first place, FormLayout is a layout, that is, a class that is responsible for positioning the widgets within a window, so it is irrelevant for these cases. On the other hand, closeEvent() should never be invoked, that is a function that serves to handle the closed window event.
Going to the point the accept method is called when Ok is pressed, so it is the right place to get the values so it must be stored in a variable, and then returned in the get_output() method:
pyformlayout.py
import sys
from PyQt5 import QtWidgets
app = QtWidgets.QApplication(sys.argv)
class Dialog(QtWidgets.QDialog):
def __init__(self, dinput):
super(Dialog, self).__init__()
self.createFormGroupBox(dinput)
buttonBox = QtWidgets.QDialogButtonBox(QtWidgets.QDialogButtonBox.Ok | QtWidgets.QDialogButtonBox.Cancel)
buttonBox.accepted.connect(self.accept)
buttonBox.rejected.connect(self.reject)
mainLayout = QtWidgets.QVBoxLayout(self)
mainLayout.addWidget(self.formGroupBox)
mainLayout.addWidget(buttonBox)
self.setWindowTitle("Form Layout")
def createFormGroupBox(self, dinput):
layout = QtWidgets.QFormLayout()
self.linedit1 = QtWidgets.QLineEdit('TestName')
self.combox1 = QtWidgets.QComboBox()
self.combox1.setToolTip('Hello')
self.combox1.addItems(['India','France','UK','USA','Germany'])
self.spinbox1 = QtWidgets.QSpinBox()
for text, w in zip(dinput, (self.linedit1, self.combox1, self.spinbox1)):
layout.addRow(text, w)
self.formGroupBox = QtWidgets.QGroupBox("Form layout")
self.formGroupBox.setLayout(layout)
def accept(self):
self._output = self.linedit1.text(), self.combox1.currentText(), self.spinbox1.value()
super(Dialog, self).accept()
def get_output(self):
return self._output
And in the file main.py I get the value if only the ok button has been pressed:
main.py
import pyformlayout as pyfl
# Staring Functions for Execution
dinput = ['LastName','Country','Age']
# Call the UI and get the inputs
dialog = pyfl.Dialog(dinput)
if dialog.exec_() == pyfl.Dialog.Accepted:
name, item, value = dialog.get_output()
print(name, item, value)
I am trying to display an image label with scrollbars within a Box layout.
However, the scroll area appears at the wrong place with the wrong size.
Could you please tell me what I am doing wrong?
import sys
from PyQt5 import QtCore
from PyQt5.QtWidgets import QApplication, QMainWindow, QVBoxLayout, QWidget, QPushButton, QLabel, QScrollArea
from PyQt5.QtGui import QPixmap
class ApplicationWindow(QMainWindow):
def __init__(self):
QMainWindow.__init__(self)
main_widget = QWidget(self)
btn = QPushButton("Bye", self)
btn.clicked.connect(self.close)
img = QPixmap("1.jpg")
label = QLabel(main_widget)
label.setPixmap(img)
scrollArea = QScrollArea(main_widget)
scrollArea.setWidgetResizable(True)
scrollArea.setWidget(label)
l = QVBoxLayout(main_widget)
l.addWidget(label)
l.addWidget(btn)
self.setCentralWidget(main_widget)
def closeEvent(self, ce):
self.close()
if __name__ == '__main__':
app = QApplication(sys.argv)
aw = ApplicationWindow()
aw.show()
app.exec_()
The result is:
The problem is that instead of adding the QLabel to QVBoxLayout you must add the QScrollArea. You must change:
l.addWidget(label)
to
l.addWidget(scrollArea)