Issue in PyQt within Python - WebBrowser Project - python

The code below is a WebBrowser code.
The problem is when I want to switch tabs which happens in the function 'SwitchTab'. I've checked that in function 'SwitchTab', my 'Tab_Content' variable is empty-as it prints 'None'- and here is the problem. I couldn't figure out why would that be empty.(I've Bolded the partS of the code which stands for the Issue)
Thanks In Advance...
P.S: I'm using Python3.8 and PyCharm4.5.4 and Also PyQt5
import sys
import os
import json
from PyQt5.QtWidgets import (QApplication, QWidget, QVBoxLayout,
QHBoxLayout, QPushButton, QLabel,
QLineEdit, QTabBar, QFrame, QStackedLayout, QTabWidget)
from PyQt5.QtGui import QIcon, QWindow, QImage
from PyQt5.QtCore import *
from PyQt5.QtWebEngineWidgets import *
class AddressBar(QLineEdit):
def __init__(self):
super().__init__()
def mousePressEvent(self, e):
self.selectAll()
class App(QFrame):
def __init__(self):
super().__init__()
self.CreateApp()
self.setWindowTitle("Web Browser")
self.setBaseSize(500 , 500)
def CreateApp(self):
self.layout = QVBoxLayout()
self.layout.setSpacing(0)
self.layout.setContentsMargins(0,0,0,0)
*#Creating Tabs*
self.TabBar = QTabBar(movable=True, tabsClosable=True)
self.TabBar.tabCloseRequested.connect(self.TabClose)
**self.TabBar.tabBarClicked.connect(self.SwitchTab)**
self.TabBar.setCurrentIndex(0)
*#Tabs List*
self.TabCount = 0
self.Tabs = []
*#Creating the AddressBar*
self.ToolBar = QWidget()
self.ToolBarLayout = QHBoxLayout()
self.AddressBar = AddressBar()
self.ToolBar.setLayout(self.ToolBarLayout)
self.ToolBarLayout.addWidget(self.AddressBar)
*#NewTab Button*
self.AddTabButton = QPushButton("+")
self.AddTabButton.clicked.connect(self.AddTab)
self.ToolBarLayout.addWidget(self.AddTabButton)
*#Main View*
self.Container = QWidget()
self.Container.layout = QStackedLayout()
self.Container.setLayout(self.Container.layout)
self.layout.addWidget(self.TabBar)
self.layout.addWidget(self.ToolBar)
self.layout.addWidget(self.Container)
self.setLayout(self.layout)
self.AddTab()
self.show()
def TabClose(self, i):
self.TabBar.removeTab(i)
print(self.TabCount)
print(self.Tabs)
def AddTab(self):
i = self.TabCount
self.Tabs.append(QWidget())
self.Tabs[i].layout = QVBoxLayout()
self.Tabs[i].setObjectName("Tab " + str(i))
*#Generate WebView*
self.Tabs[i].content = QWebEngineView()
self.Tabs[i].content.load(QUrl.fromUserInput("http://google.com"))
*#Add WebView to Tabs layout*
self.Tabs[i].layout.addWidget(self.Tabs[i].content)
*#Set top level tab [] to layout*
self.Tabs[i].setLayout(self.Tabs[i].layout)
*#Add tab to top level StackedWidget*
self.Container.layout.addWidget(self.Tabs[i])
self.Container.layout.setCurrentWidget(self.Tabs[i])
*#Set the tab at top of screen*
self.TabBar.addTab("New Tab - " + str(i))
self.TabBar.setTabData(i, "tab" + str(i))
self.TabBar.setCurrentIndex(i)
self.TabCount += 1
**def SwitchTab(self, i):
Tab_Data = self.TabBar.tabData(i)
print("tab: ", Tab_Data)
Tab_Content = self.findChild(QWidget, Tab_Data)
print(Tab_Content)
self.Container.layout.setCurrentWidget(Tab_Content)**
if __name__ == "__main__":
app = QApplication(sys.argv)
window = App()
sys.exit(app.exec_())

Because the findChild method takes the objectName into it, not the tabData you set. in this case, the solution is simple. Just set the objectName and the tabData with the same parameter.
self.TabBar.setTabData(i, "Tab " + str(i))
self.Tabs[i].setObjectName("Tab " + str(i))

Related

How to change EchoMode of QLineEdit between Normal and Password

I am writing a little program, but the buttons don't work
as I expected.
I wish the text to change state when I click on the button of that text.
Here is the code to test it:
from sys import exit
from sys import argv
from PyQt6.QtWidgets import QApplication, QHBoxLayout, QPushButton, QVBoxLayout, QLabel, QWidget, QLineEdit
class MainWindow(QWidget):
def __init__(self, parent=None) -> None:
super().__init__(parent)
self.screenWidth = 1920
self.screenHeight = 1080
self.windowWidth = 1000
self.windowHeight = 800
self.setWindowTitle("test 19")
self.setGeometry((self.screenWidth - self.windowWidth) // 2, (self.screenHeight - self.windowHeight) // 2, self.windowWidth, self.windowHeight)
self.initUi()
def initUi(self) -> None:
mainLayout = QVBoxLayout()
headLayout = QHBoxLayout()
nameLabel = QLabel("Name")
headLayout.addWidget(nameLabel)
mainLayout.addItem(headLayout)
row1 = Row("google.com")
mainLayout.addItem(row1.returnValues())
row2 = Row("yahoo.com")
mainLayout.addItem(row2.returnValues())
for i in range(20):
rowi = Row(f"{i}")
mainLayout.addItem(rowi.returnValues())
self.setLayout(mainLayout)
class Row():
def __init__(self, name) -> None:
super().__init__()
self.rowLayout = QHBoxLayout()
self.nameLineEdit = QLineEdit(f"{name}")
self.nameLineEdit.setDisabled(True)
self.rowLayout.addWidget(self.nameLineEdit)
self.hiddenOrShowButton = QPushButton("")
self.hiddenOrShowButton.clicked.connect(self.hiddenOrShow)
self.rowLayout.addWidget(self.hiddenOrShowButton)
def returnValues(self) -> QHBoxLayout:
return self.rowLayout
def hiddenOrShow(self) -> None:
if self.nameLineEdit.echoMode() == QLineEdit.EchoMode.Password:
self.nameLineEdit.setEchoMode(QLineEdit.EchoMode.Normal)
else:
self.nameLineEdit.setEchoMode(QLineEdit.EchoMode.Password)
if __name__ == "__main__":
app = QApplication(argv)
window = MainWindow()
window.show()
exit(app.exec())
I expect the text to change state when I click on the button of that text.
Your best bet is to subclass QHBoxLayout, as suggested by musicamante in the comments, and your Row class isn't that far off from doing just that.
The only changes that really need to be made are to add in the subclass reference in your Row to Row(QHBoxLayout), then would want to remove the self.rowLayout line because the Row class would become the layout. and you would change all the references to it to just self instead of self.rowLayout.
For example:
from sys import exit
from sys import argv
from PyQt6.QtWidgets import QApplication, QHBoxLayout, QPushButton, QVBoxLayout, QLabel, QWidget, QLineEdit
class MainWindow(QWidget):
def __init__(self, parent=None) -> None:
super().__init__(parent)
self.screenWidth = 1920
self.screenHeight = 1080
self.windowWidth = 1000
self.windowHeight = 800
self.setWindowTitle("test 19")
self.setGeometry((self.screenWidth - self.windowWidth) // 2, (self.screenHeight - self.windowHeight) // 2, self.windowWidth, self.windowHeight)
self.initUi()
def initUi(self) -> None:
mainLayout = QVBoxLayout()
headLayout = QHBoxLayout()
nameLabel = QLabel("Name")
headLayout.addWidget(nameLabel)
mainLayout.addLayout(headLayout)
row1 = Row("google.com") # the row now is the layout
mainLayout.addLayout(row1) # so you add it directly to the main layout
row2 = Row("yahoo.com")
mainLayout.addLayout(row2) # use addLayout instead of addItem
for i in range(20):
rowi = Row(f"{i}")
mainLayout.addLayout(rowi)
self.setLayout(mainLayout)
class Row(QHBoxLayout): # use subclass declaration
def __init__(self, name):
super().__init__()
self.nameLineEdit = QLineEdit(f"{name}")
self.nameLineEdit.setDisabled(True)
self.addWidget(self.nameLineEdit) # add the widget to self
self.hiddenOrShowButton = QPushButton("")
self.hiddenOrShowButton.clicked.connect(self.hiddenOrShow)
self.addWidget(self.hiddenOrShowButton) # same thing here
# the returnValues method can be removed.
def hiddenOrShow(self) -> None:
if self.nameLineEdit.echoMode() == QLineEdit.EchoMode.Password:
self.nameLineEdit.setEchoMode(QLineEdit.EchoMode.Normal)
else:
self.nameLineEdit.setEchoMode(QLineEdit.EchoMode.Password)
if __name__ == "__main__":
app = QApplication(argv)
window = MainWindow()
window.show()
exit(app.exec())

Adding or removing a QWidget without affecting any other widgets

I have a PyQT application with a toolbar, a set of buttons, and a bottom row of additional buttons. I'd like to add a TextEdit underneath the bottom row that the user can hide or show. I would like the TextEdit to extend the bottom portion when being shown but, when the user hides it, I would like that bottom portion removed without affecting the height, width, or sizing of any other of the buttons. Imagine just taking a pair of scissors to the TextEdit section when the user hides it but then gluing it back on when the user wants it back. Is this even possible to do in PyQt? The closest I've found is the implementation below which resizes all the buttons.
from PyQt5.QtCore import Qt, QPoint, QTimer, QThread, QSize
from PyQt5.QtGui import QFont, QImage, QPainter, QPen, QPixmap
from PyQt5.QtWidgets import (
QAction, QApplication, QCheckBox, QFileDialog, QHBoxLayout, QLabel,
QMainWindow, QMenu, QMenuBar, QPlainTextEdit, QPushButton, QSpacerItem,
QSizePolicy, QFrame,
QTextEdit, QVBoxLayout, QWidget, QGridLayout, QToolButton, QComboBox
)
from PyQt5.QtWidgets import QApplication
import sys
class AppWindow(QMainWindow):
def __init__(self, main_widget):
super(AppWindow, self).__init__()
self.main_widget = main_widget
self.setCentralWidget(self.main_widget)
class AppWidget(QWidget):
def __init__(self, panels=[]):
super(AppWidget, self).__init__()
self.panels = panels
self.main_layout = QVBoxLayout(self)
self.setSizePolicy(
QSizePolicy.MinimumExpanding,
QSizePolicy.MinimumExpanding
)
self.toolbar_frame = QFrame(self)
self.toolbar_frame_layout = QHBoxLayout(self.toolbar_frame)
self.toolbar_frame_layout.addStretch()
self.log_button = QToolButton(self.toolbar_frame)
self.log_button.setText('Toggle Log')
self.toolbar_frame_layout.addWidget(self.log_button)
self.toolbar_frame.setLayout(self.toolbar_frame_layout)
self.project_frame = QFrame(self)
self.project_frame_layout = QHBoxLayout(self.project_frame)
self.project_dropdown = QComboBox(self.project_frame)
self.project_dropdown.setMinimumSize(20, 0)
self.project_refresh = QToolButton(self.project_frame)
self.project_refresh.setText('Refresh')
self.project_frame_layout.addWidget(self.project_dropdown)
self.project_frame_layout.addWidget(self.project_refresh)
self.project_frame.setLayout(self.project_frame_layout)
self.panel_frame = QFrame(self)
self.panel_frame_layout = QVBoxLayout(self.panel_frame)
for panel in panels:
self.panel_frame_layout.addWidget(panel)
self.panel_frame.setLayout(self.panel_frame_layout)
self.bottom_frame = QFrame(self)
self.bottom_frame_layout = QHBoxLayout(self.bottom_frame)
self.bottom_frame_layout.addStretch()
self.sg_button = QToolButton()
self.sg_button.setText('Extra Stuff')
self.bottom_frame_layout.addWidget(self.sg_button)
self.bottom_frame.setLayout(self.bottom_frame_layout)
self.log = QTextEdit()
self.log_frame = QFrame(self)
self.log_frame_layout = QHBoxLayout(self.log_frame)
self.log_frame_layout.addWidget(self.log)
self.log_frame.setLayout(self.log_frame_layout)
self.main_layout.addWidget(self.toolbar_frame)
self.main_layout.addWidget(self.project_frame)
self.main_layout.addWidget(self.panel_frame)
self.main_layout.addWidget(self.bottom_frame)
self.app_widgets = QWidget(self)
self.app_widgets.setLayout(self.main_layout)
self.log_widget = QWidget(self)
self.log_widget.setLayout(self.log_frame_layout)
self.total_layout = QVBoxLayout(self)
self.total_layout.addWidget(self.app_widgets)
self.total_layout.addWidget(self.log_widget)
self.setLayout(self.total_layout)
self.log_button.clicked.connect(self.toggle_log)
def toggle_log(self):
if self.log_widget.isHidden():
self.log_widget.show()
QTimer.singleShot(0, self.resize_show)
else:
self.log_widget.hide()
QTimer.singleShot(0, self.resize_hide)
# self.adjustSize() Also does not work.
def resize_show(self):
self.resize(self.width(), self.sizeHint().height())
def resize_hide(self):
self.resize(self.width(), self.minimumSizeHint().height())
class AppPanel(QWidget):
def __init__(self, sections=[]):
super(AppPanel, self).__init__()
self.setSizePolicy(
QSizePolicy.MinimumExpanding,
QSizePolicy.MinimumExpanding
)
self.layout = QVBoxLayout(self)
self.setLayout(self.layout)
self.sections = sections
for section in self.sections:
self.layout.addWidget(section)
class AppSection(QWidget):
def __init__(self, buttons=[]):
super(AppSection, self).__init__()
self.setSizePolicy(
QSizePolicy.MinimumExpanding,
QSizePolicy.MinimumExpanding
)
self.buttons = buttons
self.layout = QGridLayout()
for i, button in enumerate(self.buttons):
col = i % 2
row = i // 2
self.layout.addWidget(button, row, col)
self.setLayout(self.layout)
class AppButton(QToolButton):
def __init__(self, text=''):
super(AppButton, self).__init__()
self.setText(text)
self.setFocusPolicy(Qt.NoFocus)
self.setIconSize(QSize(50, 50))
self.setToolButtonStyle(Qt.ToolButtonTextBesideIcon)
self.setSizePolicy(QSizePolicy.MinimumExpanding, QSizePolicy.MinimumExpanding)
if __name__ == '__main__':
app = QApplication(sys.argv)
app_buttons = [AppButton(text='APPS ' + str(i)) for i in range(5)]
custom_btns = [AppButton(text='Custom ' + str(i)) for i in range(5)]
app_section = AppSection(buttons=app_buttons)
custom_section = AppSection(buttons=custom_btns)
panels = [AppPanel(sections=[app_section, custom_section])]
ex = AppWidget(panels=panels)
lw = AppWindow(main_widget=ex)
lw.show()
app.exec_()
Resizing the widget alone is not a valid solution, because it only overrides the geometry set by the layout without notifying the parent widget.
This is also important as you should not resize the widget based on its hint alone when showing the log: if you increase the size of the window while the log is hidden and then show it again, it will not occupy all the available space.
What you need to do is to access the top level window, force its layout to lay out its contents again, and use its hint to for the resize.
def resize_hide(self):
self.window().layout().activate()
self.window().resize(
self.window().width(),
self.window().minimumSizeHint().height()
)
You can set the alignment policy for your top widget:
[...]
self.total_layout.setAlignment(self.app_widgets, Qt.AlignTop)
self.setLayout(self.total_layout)
[...]
The app_widget will not be resized anymore when you hide your text edit.

How do I open an image in a separate window using a button click in PyQT5?

from PyQt5.QtWidgets import QApplication, QLabel, QWidget, QFileDialog, QPushButton, QLineEdit,QVBoxLayout, QHBoxLayout
from PyQt5.QtCore import *
from PyQt5.QtGui import QPixmap
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QDialog, QVBoxLayout
import Updated_encrypt
import sys
class Window(QWidget):
def __init__(self):
super().__init__()
self.title = 'Encrypt/Decrypt'
self.top = 200
self.left = 500
self.width = 400
self.height = 300
self.InitWindow()
def InitWindow(self):
self.setWindowTitle(self.title)
self.setGeometry(self.left, self.top, self.width, self.height)
vbox = QVBoxLayout()
self.button1 = QPushButton('Encrypt')
self.button1.clicked.connect(self.openSecondDialog)
self.button2 = QPushButton('Decrypt')
vbox.addWidget(self.button1)
vbox.addWidget(self.button2)
self.setLayout(vbox)
self.show()
def openSecondDialog(self):
hbox = QVBoxLayout()
mydialog = QDialog(self)
mydialog.show()
self.button2 = QPushButton('Check Image')
self.button2.clicked.connect(self.getImage)
hbox.addWidget(self.button2)
self.setLayout(hbox)
self.show()
def getImage(self):
hbox = QHBoxLayout()
file_Name = QFileDialog.getOpenFileName(self,
'OpenFile',
'',
'')
image_path = file_Name[0]
updatedImage = Updated_encrypt.decrypt(image_path, 123)
pixmap = QPixmap(updatedImage)
self.label.setPixmap(QPixmap(pixmap))
self.resize(pixmap.width(), pixmap.height())
App = QApplication(sys.argv)
window = Window()
sys.exit(App.exec())
I have my code set up to implement an algorithm to modify an image when my I select it from my pop up dialogue. What I am trying to accomplish is for the image to pop up in a separate window when I click the encrypt button. I can't seem to get anything to pop up in the separate window aside from the window itself. Any help would be appreciated.
You have at least the following errors:
The "hbox" created is being added to the window and not to the QDialog: self.setLayout(hbox), it must be mydialog.setLayout(hbox).
Do not use the same name for 2 different objects as they can cause problems, in your case there are 2 QPushButton assigned to the variable "self.button2".
You try to use the variable "self.label" but never believe it.
Considering the above we can make the following improvements:
Use more descriptive names to easily distinguish their function.
If you are going to have a window that has a different objective, it is better to create a class.
The above avoid the indicated problems, considering the above the solution is:
import sys
from PyQt5.QtGui import QPixmap
from PyQt5.QtWidgets import (
QApplication,
QDialog,
QFileDialog,
QHBoxLayout,
QLabel,
QPushButton,
QVBoxLayout,
QWidget,
)
import Updated_encrypt
class Dialog(QDialog):
def __init__(self, parent=None):
super().__init__(parent)
self.load_image_btn = QPushButton("Check Image")
self.load_image_btn.clicked.connect(self.load_image)
self.image_lbl = QLabel()
lay = QVBoxLayout(self)
lay.addWidget(self.load_image_btn)
lay.addWidget(self.image_lbl)
def load_image(self):
image_path, _ = QFileDialog.getOpenFileName(self, "OpenFile", "", "")
if image_path:
updatedImage = Updated_encrypt.decrypt(image_path, 123)
pixmap = QPixmap(updatedImage)
self.image_lbl.setPixmap(QPixmap(pixmap))
class Window(QWidget):
def __init__(self, parent=None):
super().__init__(parent)
self.title = "Encrypt/Decrypt"
self.InitWindow()
def InitWindow(self):
self.setWindowTitle(self.title)
self.setGeometry(200, 500, 400, 300)
self.encrypt_btn = QPushButton("Encrypt")
self.encrypt_btn.clicked.connect(self.openSecondDialog)
self.decrypt_btn = QPushButton("Decrypt")
vbox = QVBoxLayout(self)
vbox.addWidget(self.encrypt_btn)
vbox.addWidget(self.decrypt_btn)
def openSecondDialog(self):
dialog = Dialog(self)
dialog.show()
if __name__ == "__main__":
app = QApplication(sys.argv)
window = Window()
window.show()
sys.exit(app.exec())

Aligning popup widget in PyQt5

I've seen a number of replies on SO regarding this matter but not specifically to QMenu and QToolButton. Would appreciate some pointers on aligning the popup widget to the right side of the button. Here's a basic code I'm working off..
import sys
from PyQt5.QtWidgets import *
class test(QWidget):
def __init__(self):
super().__init__()
self.resize(200, 100)
layout = QHBoxLayout(self)
label = QLabel('Testing QToolButton Popup')
toolbutton = QToolButton()
toolbutton.setPopupMode(QToolButton.InstantPopup)
widget = QWidget()
widgetLayout = QHBoxLayout(widget)
widgetLabel = QLabel('Popup Text')
widgetSpinbox = QSpinBox()
widgetLayout.addWidget(widgetLabel)
widgetLayout.addWidget(widgetSpinbox)
widgetAction = QWidgetAction(toolbutton)
widgetAction.setDefaultWidget(widget)
widgetMenu = QMenu(toolbutton)
widgetMenu.addAction(widgetAction)
toolbutton.setMenu(widgetMenu)
layout.addWidget(label)
layout.addWidget(toolbutton)
if __name__ == '__main__':
app = QApplication(sys.argv)
win = test()
win.show()
sys.exit(app.exec_())
The outcome looks like this:
The Qt developer thought the default position was correct, so if you want to modify the alignment you must move the QMenu as I show below:
import sys
from PyQt5.QtCore import QPoint
from PyQt5.QtWidgets import (
QApplication,
QHBoxLayout,
QLabel,
QMenu,
QSpinBox,
QToolButton,
QWidgetAction,
QWidget,
)
class Menu(QMenu):
def showEvent(self, event):
if self.isVisible():
button = self.parentWidget()
if button is not None:
pos = button.mapToGlobal(button.rect().bottomRight())
self.move(pos - self.rect().topRight())
super().showEvent(event)
class Test(QWidget):
def __init__(self):
super().__init__()
self.resize(200, 100)
layout = QHBoxLayout(self)
label = QLabel("Testing QToolButton Popup")
toolbutton = QToolButton(popupMode=QToolButton.InstantPopup)
widgetLabel = QLabel("Popup Text")
widgetSpinbox = QSpinBox()
widget = QWidget()
widgetLayout = QHBoxLayout(widget)
widgetLayout.addWidget(widgetLabel)
widgetLayout.addWidget(widgetSpinbox)
widgetAction = QWidgetAction(toolbutton)
widgetAction.setDefaultWidget(widget)
widgetMenu = Menu(toolbutton)
widgetMenu.addAction(widgetAction)
toolbutton.setMenu(widgetMenu)
layout.addWidget(label)
layout.addWidget(toolbutton)
if __name__ == "__main__":
app = QApplication(sys.argv)
win = Test()
win.show()
sys.exit(app.exec_())

How do I print in multiple QLabel when I click the PushButton?

How do I print in multiple QLabel when I click the PushButton?, because it only works in Quantity I also want it in Item Name and Price. I tried putting multiple print_click(self) it wont work it say redefinition of unused 'print_clink'. Thanks in advance
My Code:
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QHBoxLayout, QPushButton, QLabel, QLineEdit
from PyQt5.QtCore import pyqtSlot`
class Window(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
self.ItemName = QLabel('Item Name:')
self.Item_Line = QLabel('')
self.Item_Name = QLineEdit('')
self.PriceName = QLabel('Price:')
self.Price_Line = QLabel('')
self.Price_Name = QLineEdit('')
self.QuantityName = QLabel('Quantity:')
self.Quantity_Line = QLabel('0')
self.Quantity_Name = QLineEdit()
self.Update_button = QPushButton("Update")
self.Update_button.clicked.connect(self.print_click)
self.Clear_button = QPushButton("Clear")
self.Clear_button.clicked.connect(self.clear_click)
hbox = QHBoxLayout(self)
hbox.addWidget(self.ItemName)
hbox.addWidget(self.Item_Name)
hbox.addWidget(self.PriceName)
hbox.addWidget(self.Price_Name)
hbox.addWidget(self.QuantityName)
hbox.addWidget(self.Quantity_Line)
hbox.addWidget(self.Quantity_Name)
hbox.addWidget(self.Update_button)
hbox.addWidget(self.Clear_button)
self.show()
self.Clear_button.clicked.connect(self.Item_Line.clear)
self.Clear_button.clicked.connect(self.Item_Name.clear)
self.Clear_button.clicked.connect(self.Price_Line.clear)
self.Clear_button.clicked.connect(self.Price_Name.clear)
self.Clear_button.clicked.connect(self.Quantity_Line.clear)
self.Clear_button.clicked.connect(self.Quantity_Name.clear)
#pyqtSlot()
def print_click(self):
self.Quantity_Line.setText(self.Quantity_Name.text())
def clear_click(self):
self.Quantity_Line(self.Quantity_Name.text(''))
return self.Quantity
if __name__ == "__main__":
app = QApplication(sys.argv)
win = Window()
sys.exit(app.exec_())
I'm not completely sure of the expected result but I guess there are some mistakes and redundancies in your code :
the Price_Line and Item_Line weren't added to the QHBoxLayout
the method print_click wasn't setting the text from Price_Name and Item_Name on the respective Price_Line and Item_Line.
the clear_click method wasn't really useful as you already connected the clear method of every other elements on that button.
The following code is adapted from yours, paying attention to the points mentioned above :
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QHBoxLayout, QPushButton, QLabel, QLineEdit
from PyQt5.QtCore import pyqtSlot
class Window(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
self.ItemName = QLabel('Item Name:')
self.Item_Line = QLabel('')
self.Item_Name = QLineEdit()
self.PriceName = QLabel('Price:')
self.Price_Line = QLabel('')
self.Price_Name = QLineEdit()
self.QuantityName = QLabel('Quantity:')
self.Quantity_Line = QLabel('0')
self.Quantity_Name = QLineEdit()
self.Update_button = QPushButton("Update")
self.Update_button.clicked.connect(self.print_click)
self.Clear_button = QPushButton("Clear")
hbox = QHBoxLayout(self)
hbox.addWidget(self.ItemName)
hbox.addWidget(self.Item_Line)
hbox.addWidget(self.Item_Name)
hbox.addWidget(self.PriceName)
hbox.addWidget(self.Price_Line)
hbox.addWidget(self.Price_Name)
hbox.addWidget(self.QuantityName)
hbox.addWidget(self.Quantity_Line)
hbox.addWidget(self.Quantity_Name)
hbox.addWidget(self.Update_button)
hbox.addWidget(self.Clear_button)
self.show()
self.Clear_button.clicked.connect(self.Item_Line.clear)
self.Clear_button.clicked.connect(self.Item_Name.clear)
self.Clear_button.clicked.connect(self.Price_Line.clear)
self.Clear_button.clicked.connect(self.Price_Name.clear)
self.Clear_button.clicked.connect(self.Quantity_Line.clear)
self.Clear_button.clicked.connect(self.Quantity_Name.clear)
def print_click(self):
self.Price_Line.setText(self.Price_Name.text())
self.Item_Line.setText(self.Item_Name.text())
self.Quantity_Line.setText(self.Quantity_Name.text())
if __name__ == "__main__":
app = QApplication(sys.argv)
win = Window()
sys.exit(app.exec_())

Categories

Resources