I would like to put a cursor in a blank line edit box without having to click on it.
I looked through the Reference here
http://ftp.ics.uci.edu/pub/centos0/ics-custom-build/BUILD/PyQt-x11-gpl-4.7.2/doc/html/qlineedit.html#selectionStart
I tried calling
QLineEdit.home(True)
But this did not select the lineEdit so to say.
here is a watered down version of the code
from PyQt4 import QtCore, QtGui
import sys
import os
import os.path
class Ui_Form1(QtGui.QWidget):
def __init__(self):
QtGui.QWidget.__init__(self)
self.setupUi(self)
def setupUi(self, Form):
#init stuff
Form.setObjectName("Form")
Form.resize(794, 538)
self.gridLayout = QtGui.QGridLayout(Form)
self.gridLayout.setObjectName("gridLayout")
self.hLayout = QtGui.QHBoxLayout(Form)
self.hLayout.setObjectName("hLayout")
self.vLayout = QtGui.QVBoxLayout(Form)
self.vLayout.setObjectName("vLayout")
#label for information
self.gridLayout.addLayout(self.hLayout, 0, 0)
self.hLayout.addLayout(self.vLayout, 0)
self.label = QtGui.QLabel(Form)
self.label.setObjectName("label")
#label pixmap
self.label2 = QtGui.QLabel(Form)
self.label2.setObjectName("label")
#line edit
self.lineEdit = QtGui.QLineEdit(Form)
self.lineEdit.setAlignment(QtCore.Qt.AlignCenter)
self.gridLayout.addWidget(self.lineEdit, 3,0)
self.list = QtGui.QListWidget(self)
self.list.setObjectName("outlist")
self.list.setMinimumHeight(150)
self.vLayout.addWidget(self.list, 1)
self.hLayout.addWidget(self.label, 1)
self.vLayout.addWidget(self.label2, 0)
#self.hLayout.addWidget(self.label2, 0)
self.label2.setText('line edit')
self.retranslateUi(Form)
QtCore.QMetaObject.connectSlotsByName(Form)
def retranslateUi(self, Form):
self.label.setAlignment(QtCore.Qt.AlignCenter)
self.label.setText('Picture would go here')
self.label2.setText('line edit')
self.list.addItem('cursor will disappear when this is pressed')
#press enter to update pic
#self.lineEdit.returnPressed.connect(self.update_pic)
#####sh
if __name__ == "__main__":
app = QtGui.QApplication(sys.argv)
ex = Ui_Form1()
ex.show()
sys.exit(app.exec_())
self.lineEdit.setFocus(QtCore.Qt.StrongFocus)
In PyQt5:
self.lineEdit.setFocus()
Related
I wrote the following code in order to do some calculations. I want to add a Widget like the small picture such that when I click on pushbutton I can browse a CSV file and that path is shown in a LineEdite. I need to have this Widger in the Experiment Info QGroupBox below the checkBox. But I do not know how to add all these 3 Widget in one row in this group box.
import sys
from PyQt5.QtWidgets import QMainWindow, QAction, QMenu, QApplication
from PyQt5 import QtGui, QtCore
from PyQt5 import QtWidgets
class Application(QMainWindow):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
menubar = self.menuBar()
fileMenu = menubar.addMenu('File')
run = menubar.addMenu('Run')
exit = menubar.addMenu('Exit')
impMenu = QMenu('Import', self)
impAct = QAction('Import mail', self)
impMenu.addAction(impAct)
newAct = QAction('New', self)
fileMenu.addAction(newAct)
fileMenu.addMenu(impMenu)
# ------------- Layout ---------------------------
wid =QtWidgets.QWidget(self)
self.setCentralWidget(wid)
mainLayout = QtWidgets.QVBoxLayout()
config_box = QtWidgets.QGroupBox("Configuration")
info_box = QtWidgets.QGroupBox("Info Box")
# ------------- Config Box Layut -----------------
Config_Box_Layout = QtWidgets.QGridLayout()
case_box = QtWidgets.QGroupBox("case")
operations_box = QtWidgets.QGroupBox("Operations")
Config_Box_Layout.addWidget(case_box, 0, 0)
Config_Box_Layout.addWidget(operations_box, 0, 1)
# ----------- Operations-----------------------
operation_layout = QtWidgets.QVBoxLayout()
op1 = QtWidgets.QCheckBox('Add')
op2= QtWidgets.QCheckBox('Multiplication')
operation_layout.addWidget(op1)
operation_layout.addWidget(op2)
# ----------- cases -----------------------
case_layout = QtWidgets.QVBoxLayout()
_1 = QtWidgets.QRadioButton("1")
_2 = QtWidgets.QRadioButton("2")
_3 = QtWidgets.QRadioButton("3")
case_layout.addWidget(_1)
case_layout.addWidget(_2)
case_layout.addWidget(_3)
# --------- Info Box LayOut -----------------------
Info_box_layout = QtWidgets.QVBoxLayout()
exp_input_grou = QtWidgets.QGroupBox('Experiment Info')
exp_input_layout = QtWidgets.QVBoxLayout()
version_input = QtWidgets.QComboBox()
version_input.addItem("Algo Version")
version_input.addItem("V53")
version_input.addItem("V52")
version_input.addItem("V4")
version_input.addItem("V3")
nested_folder = QtWidgets.QCheckBox('Nested Data Path')
dialog_file = QtWidgets.QFileDialog()
pushB_ = QtWidgets.QPushButton('Browse')
exp_input_layout.addWidget(version_input)
exp_input_layout.addWidget(nested_folder)
exp_input_layout.addWidget(pushB_)
exp_input_layout.addWidget(dialog_file)
exp_report = QtWidgets.QTextEdit()
progres_bar = QtWidgets.QProgressBar()
Info_box_layout.addWidget(exp_input_grou)
Info_box_layout.addWidget(exp_report)
Info_box_layout.addWidget(progres_bar)
gt_path = QtWidgets.QLineEdit()
gt_path.setFixedWidth(100)
# -------- Adding Layouts ------------------------
mainLayout.addWidget(config_box)
config_box.setLayout(Config_Box_Layout)
case_box.setLayout(case_layout)
operations_box.setLayout(operation_layout)
info_box.setLayout(Info_box_layout)
exp_input_grou.setLayout(exp_input_layout)
mainLayout.addWidget(info_box)
wid.setLayout(mainLayout)
self.setGeometry(300, 300, 300, 700)
self.setWindowTitle('Example')
app_icon = QtGui.QIcon()
app_icon.addFile('pic.jpg', QtCore.QSize(256, 256))
self.setWindowIcon(app_icon)
self.show()
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = Application()
sys.exit(app.exec_())
If you want to add widgets horizontally in a vertical layout, you have to add an horizontal layout to it. This technique is generally referred to as "nested layouts".
Then, you don't have to create a file dialog instance within the init (otherwise it will be probably shown along with the main window), and you don't have to use the QFileDialog() constructor for your needs, since QDialog already provides static methods that easily allow you to open a standard dialog and get the selected file(s) or directory.
class Application(QMainWindow):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
# ...
# --------- Info Box LayOut -----------------------
Info_box_layout = QtWidgets.QVBoxLayout()
exp_input_grou = QtWidgets.QGroupBox('Experiment Info')
exp_input_layout = QtWidgets.QVBoxLayout()
version_input = QtWidgets.QComboBox()
version_input.addItem("Algo Version")
version_input.addItem("V53")
version_input.addItem("V52")
version_input.addItem("V4")
version_input.addItem("V3")
nested_folder = QtWidgets.QCheckBox('Nested Data Path')
# This should not be here!!!
# dialog_file = QtWidgets.QFileDialog()
exp_input_layout.addWidget(version_input)
exp_input_layout.addWidget(nested_folder)
browse_layout = QtWidgets.QHBoxLayout()
exp_input_layout.addLayout(browse_layout)
self.gt_path = QtWidgets.QLineEdit()
pushB_ = QtWidgets.QPushButton('Browse')
pushB_.clicked.connect(self.browse_path)
browse_layout.addWidget(self.gt_path)
browse_layout.addWidget(pushB_)
# ...
def browse_path(self):
path, filter = QtWidgets.QFileDialog.getOpenFileName(self, 'Select file',
'', 'CSV files (*.csv);;All files (*)')
if path:
self.gt_path.setText(path)
QGridLayout is also a valid alternative, but it doesn't work fine with everything, as its sizes are always dependent on the size of widgets each row or column contains. Your case is very simple, so it can be used without problems:
def initUI(self):
# ...
# --------- Info Box LayOut -----------------------
Info_box_layout = QtWidgets.QVBoxLayout()
exp_input_grou = QtWidgets.QGroupBox('Experiment Info')
exp_input_layout = QtWidgets.QGridLayout()
version_input = QtWidgets.QComboBox()
version_input.addItem("Algo Version")
version_input.addItem("V53")
version_input.addItem("V52")
version_input.addItem("V4")
version_input.addItem("V3")
nested_folder = QtWidgets.QCheckBox('Nested Data Path')
self.gt_path = QtWidgets.QLineEdit()
pushB_ = QtWidgets.QPushButton('Browse')
pushB_.clicked.connect(self.browse_path)
# add the combobox to the first row, first column, but set its column
# span to 2, meaning that it occupies two "columns"
exp_input_layout.addWidget(version_input, 0, 0, 1, 2)
# the same for the checkbox, but on the second row
exp_input_layout.addWidget(nested_folder, 1, 0, 1, 2)
# add the line edit, third row, first column; if you don't specify the
# span, the widget will only occupy one "cell" of the grid layout
exp_input_layout.addWidget(self.gt_path, 2, 0)
# and the button, same row, second column
exp_input_layout.addWidget(pushB_, 2, 1)
# ...
The below code will do what you want, you just need to implement it into your code:
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(387, 224)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.gridLayout = QtWidgets.QGridLayout(self.centralwidget)
self.gridLayout.setObjectName("gridLayout")
self.lineEdit = QtWidgets.QLineEdit(self.centralwidget)
self.lineEdit.setObjectName("lineEdit")
self.lineEdit.setReadOnly(True)
self.label = QtWidgets.QLabel(self.centralwidget)
self.label.setObjectName("label")
self.pushButton = QtWidgets.QPushButton(self.centralwidget)
self.pushButton.setObjectName("pushButton")
self.pushButton.clicked.connect(self.open_file)
self.gridLayout.addWidget(self.lineEdit, 0, 1, 1, 1)
self.gridLayout.addWidget(self.label, 0, 0, 1, 1)
self.gridLayout.addWidget(self.pushButton, 0, 2, 1, 1)
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 387, 21))
self.menubar.setObjectName("menubar")
MainWindow.setMenuBar(self.menubar)
self.statusbar = QtWidgets.QStatusBar(MainWindow)
self.statusbar.setObjectName("statusbar")
MainWindow.setStatusBar(self.statusbar)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
self.label.setText(_translate("MainWindow", "Select output file"))
self.pushButton.setText(_translate("MainWindow", "..."))
def open_file(self):
self.file_name = QtWidgets.QFileDialog.getOpenFileName(None, "Open", "", "CSV Files (*.csv)")
if self.file_name[0] != '':
self.lineEdit.setText(self.file_name[0])
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
MainWindow = QtWidgets.QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
MainWindow.show()
sys.exit(app.exec_())
Output:
I want to display a downward facing arrow (or any shape really) in QT designer between two lineEdits. This seems simple, but I can't seem to find an answer. I have code below that shows what I am trying to do. Any help is greatly appreciated!
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtGui import QPainter, QBrush, QPen
from PyQt5.QtCore import Qt
class Ui_Frame(object):
def setupUi(self, Frame):
Frame.setObjectName("Frame")
Frame.resize(472, 408)
Frame.setFrameShape(QtWidgets.QFrame.StyledPanel)
Frame.setFrameShadow(QtWidgets.QFrame.Raised)
self.verticalLayout = QtWidgets.QVBoxLayout(Frame)
self.verticalLayout.setObjectName("verticalLayout")
self.lineEdit = QtWidgets.QLineEdit(Frame)
self.lineEdit.setAlignment(QtCore.Qt.AlignCenter)
self.lineEdit.setObjectName("lineEdit")
self.verticalLayout.addWidget(self.lineEdit)
self.frame = QtWidgets.QFrame(Frame)
self.frame.setFrameShape(QtWidgets.QFrame.StyledPanel)
self.frame.setFrameShadow(QtWidgets.QFrame.Raised)
self.frame.setObjectName("frame")
self.verticalLayout_2 = QtWidgets.QVBoxLayout(self.frame)
self.verticalLayout_2.setObjectName("verticalLayout_2")
self.frame_3 = QtWidgets.QFrame(self.frame)
self.frame_3.setFrameShape(QtWidgets.QFrame.StyledPanel)
self.frame_3.setFrameShadow(QtWidgets.QFrame.Raised)
self.frame_3.setObjectName("frame_3")
self.horizontalLayout_2 = QtWidgets.QHBoxLayout(self.frame_3)
self.horizontalLayout_2.setObjectName("horizontalLayout_2")
self.label_2 = QtWidgets.QLabel(self.frame_3)
self.label_2.setObjectName("label_2")
self.horizontalLayout_2.addWidget(self.label_2)
self.lineEdit_4 = QtWidgets.QLineEdit(self.frame_3)
self.lineEdit_4.setObjectName("lineEdit_4")
self.horizontalLayout_2.addWidget(self.lineEdit_4)
self.verticalLayout_2.addWidget(self.frame_3)
# I would like to paint a shape on this frame (frame_paint) using method paintEvent
self.frame_paint = QtWidgets.QFrame(self.frame)
self.frame_paint.setFrameShape(QtWidgets.QFrame.StyledPanel)
self.frame_paint.setFrameShadow(QtWidgets.QFrame.Raised)
self.frame_paint.setObjectName("frame_paint")
self.verticalLayout_2.addWidget(self.frame_paint)
self.frame_2 = QtWidgets.QFrame(self.frame)
self.frame_2.setFrameShape(QtWidgets.QFrame.StyledPanel)
self.frame_2.setFrameShadow(QtWidgets.QFrame.Raised)
self.frame_2.setObjectName("frame_2")
self.horizontalLayout = QtWidgets.QHBoxLayout(self.frame_2)
self.horizontalLayout.setObjectName("horizontalLayout")
self.label = QtWidgets.QLabel(self.frame_2)
self.label.setObjectName("label")
self.horizontalLayout.addWidget(self.label)
self.lineEdit_3 = QtWidgets.QLineEdit(self.frame_2)
self.lineEdit_3.setObjectName("lineEdit_3")
self.horizontalLayout.addWidget(self.lineEdit_3)
self.verticalLayout_2.addWidget(self.frame_2)
self.verticalLayout.addWidget(self.frame)
self.retranslateUi(Frame)
QtCore.QMetaObject.connectSlotsByName(Frame)
def retranslateUi(self, Frame):
_translate = QtCore.QCoreApplication.translate
Frame.setWindowTitle(_translate("Frame", "Frame"))
self.lineEdit.setText(_translate("Frame", "(Name of research project)"))
self.label_2.setText(_translate("Frame", "Level 1:"))
self.label.setText(_translate("Frame", "Level 2:"))
### I want this paintEvent to go to the self.frame_paint
def paintEvent(self, e):
painter = QPainter(self)
painter.setPen(QPen(Qt.black, 10, Qt.SolidLine))
painter.drawRect(100, 15, 400, 200)
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
Frame = QtWidgets.QFrame()
ui = Ui_Frame()
ui.setupUi(Frame)
Frame.show()
sys.exit(app.exec_())
After some time, I figured it out. I was missing the whole thing about having two py files and implementing painting on a scene. Here is my code that works.
class MainWindow_RUA(QtWidgets.QMainWindow, Ui_MainWindow_RUA):
def __init__(self, parent=None):
super(MainWindow_RUA, self).__init__(parent)
self.setupUi(self)
scene = Painter()
self.graphicsView.setScene(scene)
class Painter(QtWidgets.QGraphicsScene):
def __init__(self, parent=None):
super().__init__(parent)
pen = QtGui.QPen(QtGui.QColor(QtCore.Qt.black))
pen.setWidth(2)
brush = QtGui.QBrush(pen.color().darker(150))
self.addLine(100, 200, 100, 100, pen)
self.addLine(85, 175, 100, 200, pen)
self.addLine(100, 200, 115, 175, pen)
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
application = MainWindow_RUA()
application.show()
sys.exit(app.exec_())
In my main program, I have a Dock widget (Vertical layout) containing a TabWidget (layouts added per tab). In my first tab I have added a static table, which resizes with the dock.
I am trying to allow the user to dynamically add a tab by importing a TableWidget design from another file into a tab; however, I am having trouble getting the layout to mimic the first tab.
Below is my code. I can make the table appear in the freshly made tab, just not fully adjust to the dock window.
My python start file:
from PyQt5 import QtCore, QtWidgets, QtGui
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
import mainwindow, sys, os, PyQt5, resources, dataTable
class dataForm(QtWidgets.QWidget, dataTable.Ui_Form)
def __init__(self, parent=None):
super(dataForm, self).__init__(parent)
self.setupUi(self)
class Example(QtWidgets.QMainWindow, mainwindow.Ui_MainWindow):
def __init__(self, parent=None):
super(Example, self).__init__(parent)
self.setupUi(self)
self.shortcut.activated.connect(self.addTabs)
def Resolution(self):
app = QtWidgets.QApplication([])
resolution = app.desktop().screenGeometry()
width, height = resolution.width(), resolution.height()
self.setMaximumSize(QtCore.QSize(width, height))
def addTabs(self):
self.DataSets.setUpdatesEnabled(True)
self.tab = QtWidgets.QWidget()
self.tab.setAutoFillBackground(False)
self.tab.setObjectName("userAdded")
pages = self.count()
# Set the tab layout
self.tableLayout = QtWidgets.QVBoxLayout(self.tab)
self.tableLayout.setContentsMargins(1, 0, 1, 0)
self.tableLayout.setSpacing(0)
self.tableLayout.setObjectName("tableGrid")
# Add table to the new tab widget
self.table = dataForm(self.tab)
# Add table to layout
self.tableLayout.addWidget(self.table)
self.tableLayout.addStretch()
# Add the tab and go to that location
self.DataSets.insertTab((pages-1), self.tab, "Set %d" %(pages))
self.DataSets.setCurrentIndex(pages-1)
def main():
app = QtWidgets.QApplication(sys.argv)
form = Example()
form.showMaximized()
app.exec_()
if __name__ == '__main__':
main()
and my dataTable.ui form:
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_Form(object):
def setupUi(self, Form):
Form.setObjectName("Form")
Form.resize(242, 450)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(Form.sizePolicy().hasHeightForWidth())
Form.setSizePolicy(sizePolicy)
self.tableWidget = QtWidgets.QTableWidget(Form)
self.tableWidget.setGeometry(QtCore.QRect(1, 0, 240, 450))
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.tableWidget.sizePolicy().hasHeightForWidth())
self.tableWidget.setSizePolicy(sizePolicy)
self.tableWidget.setContextMenuPolicy(QtCore.Qt.DefaultContextMenu)
self.tableWidget.setAutoFillBackground(True)
self.tableWidget.setStyleSheet("QHeaderView::section { background-color:rgb(140, 200, 172)};\n"
"")
self.tableWidget.setFrameShape(QtWidgets.QFrame.Panel)
self.tableWidget.setFrameShadow(QtWidgets.QFrame.Plain)
self.tableWidget.setSizeAdjustPolicy(QtWidgets.QAbstractScrollArea.AdjustToContentsOnFirstShow)
self.tableWidget.setDragEnabled(True)
self.tableWidget.setAlternatingRowColors(True)
self.tableWidget.setGridStyle(QtCore.Qt.SolidLine)
self.tableWidget.setRowCount(35)
self.tableWidget.setColumnCount(10)
self.tableWidget.setObjectName("tableWidget")
item = QtWidgets.QTableWidgetItem()
brush = QtGui.QBrush(QtGui.QColor(50, 0, 0))
brush.setStyle(QtCore.Qt.NoBrush)
item.setForeground(brush)
self.tableWidget.setItem(0, 1, item)
self.tableWidget.horizontalHeader().setCascadingSectionResizes(False)
self.tableWidget.horizontalHeader().setDefaultSectionSize(70)
self.tableWidget.horizontalHeader().setHighlightSections(True)
self.tableWidget.horizontalHeader().setMinimumSectionSize(39)
self.tableWidget.verticalHeader().setVisible(True)
self.tableWidget.verticalHeader().setDefaultSectionSize(20)
self.tableWidget.verticalHeader().setSortIndicatorShown(True)
self.tableWidget.verticalHeader().setStretchLastSection(False)
self.retranslateUi(Form)
QtCore.QMetaObject.connectSlotsByName(Form)
def retranslateUi(self, Form):
_translate = QtCore.QCoreApplication.translate
Form.setWindowTitle(_translate("Form", "Form"))
self.tableWidget.setSortingEnabled(True)
__sortingEnabled = self.tableWidget.isSortingEnabled()
self.tableWidget.setSortingEnabled(False)
self.tableWidget.setSortingEnabled(__sortingEnabled)
I'm pretty close, I think. Any suggestions?
Edit: Updated code to make the dataTable classified as a QWidget & passed self.tab as its parent in def AddTabs. Also, I added a part of the layout of AddTabs that was cut out accidentally.
I can't get to work a custom dialog made in Qt Designer. I understand how can i popup the dialog but i can't get the data from that line text.
main program.py
from PyQt5 import QtCore, QtGui, QtWidgets
from ui import Ui_MainWindow
from addui import Ui_Dialog as Form
from bs4 import BeautifulSoup
import requests
import time
import sys
class MainDialog(QtWidgets.QMainWindow, Ui_MainWindow):
def __init__(self):
super(self.__class__, self).__init__()
self.setupUi(self)
self.actionRefresh.triggered.connect(self.refresh_btn)
self.actionAdd.triggered.connect(self.add_btn)
self.actionRemove.triggered.connect(self.remove_btn)
self.actionSettings.triggered.connect(self.settings_btn)
self.actionAbout.triggered.connect(self.about_btn)
self.actionExit.triggered.connect(self.exit_btn)
def open_dialog(self):
dialog = QtWidgets.QDialog()
dialog.ui = Form()
dialog.ui.setupUi(dialog)
dialog.exec_()
dialog.show()
def refresh_btn(self):
print('Refresh')
self.getting_data()
def add_btn(self):
print('Add')
self.open_dialog()
def remove_btn(self):
print('Remove')
def settings_btn(self):
print('Settings')
QtWidgets.QMessageBox.warning(self, 'Settings',
'Work in progress.\n'
' Coming soon!')
def about_btn(self):
print('About')
QtWidgets.QMessageBox.about(self, 'About Checking Prices',
'Checking Prices - Beta v1.0\n'
'\n'
'Copyright(c) 2015 - Pifu Valentin')
def exit_btn(self):
self.close()
def getting_data(self):
links = ['link1',
'link2',
'link3'
]
self.statusBar.showMessage('Getting data...')
try:
for nr, link in enumerate(links, start=1):
cont = requests.get(link)
soup = BeautifulSoup(cont.content, "html.parser")
title = soup.title.text[:40]
price = soup.find('span', {'itemprop': 'price'}).text
linetxt = ('{}. {} >> ${}').format(nr, title, price)
if nr == 1:
self.linetxt1.setText(linetxt)
elif nr == 2:
self.linetxt2.setText(linetxt)
elif nr == 3:
self.linetxt3.setText(linetxt)
self.statusBar.showMessage('Last updated - '+time.strftime('%H:%M:%S'))
except:
self.statusBar.showMessage('Error getting data.')
def main():
app = QtWidgets.QApplication(sys.argv)
form = MainDialog()
form.show()
app.exec_()
if __name__ == '__main__':
main()
addui.py (dialog)
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_Dialog(object):
def setupUi(self, Dialog):
Dialog.setObjectName("Dialog")
Dialog.resize(200, 71)
Dialog.setMinimumSize(QtCore.QSize(200, 71))
Dialog.setMaximumSize(QtCore.QSize(200, 71))
Dialog.setContextMenuPolicy(QtCore.Qt.NoContextMenu)
icon = QtGui.QIcon()
icon.addPixmap(QtGui.QPixmap("Icons/Plus-32.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
Dialog.setWindowIcon(icon)
self.gridLayout = QtWidgets.QGridLayout(Dialog)
self.gridLayout.setObjectName("gridLayout")
self.text_link = QtWidgets.QLineEdit(Dialog)
self.text_link.setObjectName("text_link")
self.gridLayout.addWidget(self.text_link, 0, 0, 1, 2)
self.add_link = QtWidgets.QPushButton(Dialog)
self.add_link.setObjectName("add_link")
self.gridLayout.addWidget(self.add_link, 1, 0, 1, 1)
self.cancel_link = QtWidgets.QPushButton(Dialog)
self.cancel_link.setObjectName("cancel_link")
self.gridLayout.addWidget(self.cancel_link, 1, 1, 1, 1)
self.retranslateUi(Dialog)
self.cancel_link.clicked.connect(self.exit_dialog)
self.add_link.clicked.connect(self.get_link)
def retranslateUi(self, Dialog):
_translate = QtCore.QCoreApplication.translate
Dialog.setWindowTitle(_translate("Dialog", "Add link"))
self.add_link.setText(_translate("Dialog", "Add"))
self.cancel_link.setText(_translate("Dialog", "Cancel"))
def get_link(self):
print(self.text_link.text())
x = self.text_link.text()
return x
def exit_dialog(self):
self.destroy()
I have some problems with this program.
If i click on cancel to exit only the dialog not the main program. (i tried with self.close, self.hide...)
I want to add a link on that line_text and to get that link to the main program, but when i click on add to close dialog and data pass to the main program.
It's ok how i call the dialog ?
def open_dialog(self):
dialog = QtWidgets.QDialog()
dialog.ui = Form()
dialog.ui.setupUi(dialog)
dialog.exec_()
dialog.show()
Thanks. I don't get how i can do this, hope someone can help.
THanks again.
You need to exec_() to do this and Here is a minimal version of your code which is fixed
from PyQt4 import QtCore, QtGui
import sys
class PopUpDLG(QtGui.QDialog):
def __init__(self):
super(PopUpDLG, self).__init__()
self.setObjectName("self")
self.resize(200, 71)
self.setMinimumSize(QtCore.QSize(200, 71))
self.setMaximumSize(QtCore.QSize(200, 71))
self.setContextMenuPolicy(QtCore.Qt.NoContextMenu)
icon = QtGui.QIcon()
icon.addPixmap(QtGui.QPixmap("Icons/Plus-32.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
self.setWindowIcon(icon)
self.gridLayout = QtGui.QGridLayout(self)
self.gridLayout.setObjectName("gridLayout")
self.text_link = QtGui.QLineEdit(self)
self.text_link.setObjectName("text_link")
self.gridLayout.addWidget(self.text_link, 0, 0, 1, 2)
self.add_link = QtGui.QPushButton(self)
self.add_link.setObjectName("add_link")
self.gridLayout.addWidget(self.add_link, 1, 0, 1, 1)
self.cancel_link = QtGui.QPushButton(self)
self.cancel_link.setObjectName("cancel_link")
self.gridLayout.addWidget(self.cancel_link, 1, 1, 1, 1)
self.retranslateUi(self)
self.cancel_link.clicked.connect(self.reject)
self.add_link.clicked.connect(self.get_link)
self.retrunVal = None
def retranslateUi(self, Dialog):
_translate = QtCore.QCoreApplication.translate
self.setWindowTitle(_translate("Dialog", "Add link"))
self.add_link.setText(_translate("Dialog", "Add"))
self.cancel_link.setText(_translate("Dialog", "Cancel"))
def get_link(self):
self.retrunVal = self.text_link.text()
self.accept()
def exec_(self):
super(PopUpDLG, self).exec_()
return self.retrunVal
class MainDialog(QtGui.QMainWindow):
def __init__(self):
super(self.__class__, self).__init__()
centralwidget = QtGui.QWidget(self)
self.layout = QtGui.QHBoxLayout(centralwidget)
self.button = QtGui.QPushButton("Open")
self.valText = QtGui.QLabel("")
self.layout.addWidget(self.button)
self.layout.addWidget(self.valText)
self.setCentralWidget(centralwidget)
self.button.clicked.connect(self.open_dialog)
def open_dialog(self):
dialog = PopUpDLG()
value = dialog.exec_()
if value:
self.valText.setText(value)
def main():
app = QtGui.QApplication(sys.argv)
form = MainDialog()
form.show()
app.exec_()
if __name__ == '__main__':
main()
I am trying to access all the buttons, labels, text widgets, etc inside nested QVBoxLayout and QHBoxLayout layouts using the children() method. But I am not getting the results I expect: I am only getting the layouts but not the buttons, labels, etc.
Is there a Pythonic way of iterating through all the nested layouts to obtain the buttons, labels, textedit, etc.?
Here is the part where I am having trouble:
for child in self.ui.gridLayout.children():
print "child_name:%s - type:%s" %(child.objectName(),type(child))
for grand_child in child.children():
print "gc_name:%s - type:%s" %(grand_child.objectName(),type(grand_child))
# never prints the buttons, labels, etc
for ggc in grand_child.children():
print "ggc_name:%s - type:%s" %(ggc.objectName(),type(ggc))
# never finds the QLabels
qreg = QRegExp('.+')
widgets = grand_child.findChildren(QLabel,qreg)
print widgets # prints None
Here is the whole code:
import sys
from PyQt4 import QtCore, QtGui
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from mygui import Ui_Form
class MyApp(QtGui.QWidget):
def __init__(self,parent=None):
super(MyApp, self).__init__(parent)
self.ui = Ui_Form()
self.ui.setupUi(self)
self.ui.pushButton_test.clicked.connect(self.click_button)
def click_button(self):
print "Printing layouts and widgets"
for child in self.ui.gridLayout.children():
print "child_name:%s - type:%s" %(child.objectName(),type(child))
for grand_child in child.children():
print "gc_name:%s - type:%s" %(grand_child.objectName(),type(grand_child))
# never prints
for ggc in grand_child.children():
print "ggc_name:%s - type:%s" %(ggc.objectName(),type(ggc))
qreg = QRegExp('.+')
widgets = grand_child.findChildren(QLabel,qreg)
print widgets # prints None
if __name__ == "__main__":
app = QtGui.QApplication(sys.argv)
myapp = MyApp()
myapp.show()
sys.exit(app.exec_())
And here's mygui.py:
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'mygui.ui'
#
# Created: Thu Mar 28 14:07:12 2013
# by: PyQt4 UI code generator 4.9.1
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
_fromUtf8 = lambda s: s
class Ui_Form(object):
def setupUi(self, Form):
Form.setObjectName(_fromUtf8("Form"))
Form.resize(454, 323)
self.gridLayout = QtGui.QGridLayout(Form)
self.gridLayout.setObjectName(_fromUtf8("gridLayout"))
self.verticalLayout = QtGui.QVBoxLayout()
self.verticalLayout.setObjectName(_fromUtf8("verticalLayout"))
self.horizontalLayout = QtGui.QHBoxLayout()
self.horizontalLayout.setObjectName(_fromUtf8("horizontalLayout"))
self.lineEdit = QtGui.QLineEdit(Form)
self.lineEdit.setObjectName(_fromUtf8("lineEdit"))
self.horizontalLayout.addWidget(self.lineEdit)
self.pushButton_2 = QtGui.QPushButton(Form)
self.pushButton_2.setObjectName(_fromUtf8("pushButton_2"))
self.horizontalLayout.addWidget(self.pushButton_2)
self.verticalLayout.addLayout(self.horizontalLayout)
self.horizontalLayout_2 = QtGui.QHBoxLayout()
self.horizontalLayout_2.setObjectName(_fromUtf8("horizontalLayout_2"))
self.label_2 = QtGui.QLabel(Form)
self.label_2.setObjectName(_fromUtf8("label_2"))
self.horizontalLayout_2.addWidget(self.label_2)
self.label = QtGui.QLabel(Form)
self.label.setObjectName(_fromUtf8("label"))
self.horizontalLayout_2.addWidget(self.label)
self.verticalLayout.addLayout(self.horizontalLayout_2)
self.textEdit = QtGui.QTextEdit(Form)
self.textEdit.setObjectName(_fromUtf8("textEdit"))
self.verticalLayout.addWidget(self.textEdit)
self.pushButton_test = QtGui.QPushButton(Form)
self.pushButton_test.setObjectName(_fromUtf8("pushButton_test"))
self.verticalLayout.addWidget(self.pushButton_test)
self.gridLayout.addLayout(self.verticalLayout, 0, 0, 1, 1)
self.retranslateUi(Form)
QtCore.QMetaObject.connectSlotsByName(Form)
def retranslateUi(self, Form):
Form.setWindowTitle(QtGui.QApplication.translate("Form", "Form", None, QtGui.QApplication.UnicodeUTF8))
self.pushButton_2.setText(QtGui.QApplication.translate("Form", "PushButton", None, QtGui.QApplication.UnicodeUTF8))
self.label_2.setText(QtGui.QApplication.translate("Form", "TextLabel", None, QtGui.QApplication.UnicodeUTF8))
self.label.setText(QtGui.QApplication.translate("Form", "TextLabel", None, QtGui.QApplication.UnicodeUTF8))
self.pushButton_test.setText(QtGui.QApplication.translate("Form", "Print All Widgets", None, QtGui.QApplication.UnicodeUTF8))
if __name__ == "__main__":
import sys
app = QtGui.QApplication(sys.argv)
Form = QtGui.QWidget()
ui = Ui_Form()
ui.setupUi(Form)
Form.show()
sys.exit(app.exec_())
I appreciate your help and input.
Paul
I realized that all the widgets can be accessed from self. Here is the final code I used:
wtypes = [QPushButton,QLabel,QTextEdit]
qreg = QRegExp(r'.*')
mywidgets = {}
for t in wtypes:
mywidgets[t] = self.findChildren(t,qreg)
for button in mywidgets[QPushButton]:
print "button:", button.objectName()
for label in mywidgets[QLabel]:
print "label:", label.objectName()