How to change EchoMode of QLineEdit between Normal and Password - python

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())

Related

Detect Slider move

I want to be able to detect if the slider has moved to a new position and then do some actions in another function called sl. Here is my code:
import sys
from PyQt5 import QtWidgets
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QApplication, QLabel, QLineEdit, QScrollBar, QMainWindow, QMenu, QWidget, QGridLayout, \
QMessageBox, QListWidget, QPlainTextEdit, QTableWidget, QTableWidgetItem, QHeaderView
from PyQt5.QtWidgets import QMenuBar, QHBoxLayout, QVBoxLayout, QSlider, QPushButton, QDial, QBoxLayout, QSpacerItem
from PyQt5.QtGui import QFont, QColor, QPixmap, QResizeEvent, QPen
import PyQt5.QtGui as QtGui
import PyQt5.QtCore as QtCore
class ControlWidget(QWidget):
def __init__(self):
QWidget.__init__(self)
self.layout = QVBoxLayout()
self.layout.setContentsMargins(10, 10, 10, 10)
widget3 = QLabel("Manual")
big_font = QFont('Arial')
big_font.setPointSize(15)
widget3.setFont(big_font)
self.layout.addWidget(widget3, stretch=1)
widget2 = ManualWidget()
self.layout.addWidget(widget2, stretch=4)
self.setLayout(self.layout)
class ManualWidget(QWidget):
def __init__(self):
QWidget.__init__(self)
self.layout = QHBoxLayout()
right_widget = QWidget()
right_layout = QVBoxLayout()
right_top_widget = QWidget()
self.sld1 = self.slider('V1:', 0, 100)
right_top_layout = QVBoxLayout()
right_top_layout.setContentsMargins(0, 0, 0, 0)
right_top_layout.addWidget(self.sld1, stretch=1)
right_top_widget.setLayout(right_top_layout)
right_layout.addWidget(right_top_widget)
right_widget.setLayout(right_layout)
self.layout.addWidget(right_widget, stretch=1)
self.setLayout(self.layout)
self.layout.addWidget(self.name)
self.layout.addWidget(self.label)
self.layout.addWidget(self.slider)
print(self.sl())
def slider(self, name, low, high, step=10):
self.name = QLabel(str(name))
self.label = QLabel(str(low))
self.slider = QSlider(Qt.Horizontal, self)
self.slider.setMinimum(low)
self.slider.setMaximum(high*step)
self.slider.setValue(low)
self.slider.valueChanged.connect(self.change_value)
self.action = False
self.slider.sliderMoved.connect(self.act1)
def change_value(self):
self.set_point = (float(self.slider.value())) / 10
self.label.setText(str(self.set_point))
def act1(self):
self.action = True
return self.action
def sl(self):
if self.action == True:
x = 3
else:
x = 6
return x
class MainWidget(QWidget):
def __init__(self):
QWidget.__init__(self)
self.layout = QVBoxLayout()
self.layout.setContentsMargins(0, 0, 0, 0)
big_font = QFont('Arial')
big_font.setPointSize(10)
bottom_widget = ControlWidget()
self.layout.addWidget(bottom_widget, stretch=10)
self.setLayout(self.layout)
class Window(QMainWindow):
def __init__(self, widget):
QMainWindow.__init__(self)
self.setWindowTitle("Flow test rig")
self.menu = self.menuBar()
self.setCentralWidget(widget)
self.status = self.statusBar()
widget.parent = self
app = QApplication(sys.argv)
main_widget = MainWidget()
win = Window(main_widget)
win.show()
sys.exit(app.exec_())
I tried to detect it with the act1 function, however, self.action is always False, or when it becomes True, it does not reset to False after the first move of the slider. I appreciate it if someone would help me.

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())

Looking to fix size policy and how scrollArea shows in a tab

so I am trying to use PyQt5 to put a scroll area inside of a tab. Just playing around with a system that reads the serial port.
The issue I am having is that although I set a QVBoxLayout, the size does not seem to adjust to what I want it to be. It seems to be taking its minimum size and not adjusting.
I tried looking at the documentation on QSizePolicy on the website provided, but unfortunately it is all labeled as TODO.
https://www.riverbankcomputing.com/static/Docs/PyQt5/api/qtwidgets/qsizepolicy.html
I was wondering if anyone had some experience with this?
import sys
from PyQt5.QtWidgets import QMainWindow, QSizePolicy, QLabel, QGridLayout, QToolTip, QPlainTextEdit, QScrollArea, QApplication, QPushButton, QWidget, QAction, QTabWidget, QHBoxLayout, QVBoxLayout
from PyQt5.QtGui import *
from PyQt5.QtCore import pyqtSlot, QDateTime, Qt, pyqtSignal, QObject, QSize
import datetime
import serial
import serial.tools.list_ports
import threading
class FDSerial(QMainWindow):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
self.connected = False
self.fd_line = ""
newAct = QAction(QIcon('icn/001-file.png'), 'New', self)
newAct.triggered.connect(self.init_sc)
self.toolbar = self.addToolBar('New')
self.toolbar.addAction(newAct)
openAct = QAction(QIcon('icn/002-folder.png'), 'Open', self)
self.toolbar.addAction(openAct)
connectAct = QAction(QIcon('icn/003-pendrive.png'), 'Connect', self)
connectAct.triggered.connect(self.find_port)
self.toolbar.addAction(connectAct)
menubar = self.menuBar()
fileMenu = menubar.addMenu('&File')
editMenu = menubar.addMenu('&Settings')
toolsMenu = menubar.addMenu('&Tools')
sessionMenu = menubar.addMenu('&Session')
helpMenu = menubar.addMenu('&Help')
self.statusBar().showMessage('Ready')
self.table_widget = LayoutWidgets(self)
self.setCentralWidget(self.table_widget)
self.setGeometry(400, 400, 800, 600)
self.setWindowTitle('FD Serial Demo')
self.show()
self.c = Communicate()
self.c.serialStuff.connect(lambda: self.table_widget.add_row(self.fd_line))
def init_sc(self):
self.ser = serial.Serial()
self.ser.baudrate = 115200
self.is_connected = False
self.tests_run = 0
self.port_found = False
def find_port(self):
if self.is_connected is False:
self.is_connected = True
else:
self.is_connected = False
for port in serial.tools.list_ports.comports():
if port.vid == 5824 and port.pid == 1155:
self.ser.port = str(port.device)
self.port_found = True
print("Found")
if self.port_found is False:
print("Not found")
x = threading.Thread(target=self.talk_module)
x.start()
def talk_module(self):
self.ser.open()
while self.is_connected is True:
self.fd_line = self.ser.readline().decode()
print(self.fd_line)
self.c.serialStuff.emit()
self.ser.close()
class Communicate(QObject):
serialStuff = pyqtSignal()
class LayoutWidgets(QWidget):
def __init__(self, parent):
super(QWidget, self).__init__(parent)
self.layout = QVBoxLayout(self)
self.thisthat = 0
self.mySizePolicy = QSizePolicy()
self.mySizePolicy.setHorizontalStretch(1)
self.mySizePolicy.setVerticalStretch(1)
# self.mySizePolicy.setHeightForWidth(False)
# self.mySizePolicy.setHorizontalPolicy(QSizePolicy.Maximum)
# self.mySizePolicy.setVerticalPolicy(QSizePolicy.Maximum)
self.tabs = QTabWidget()
self.tab1 = QWidget()
self.tab2 = QWidget()
self.tabs.addTab(self.tab1, "Serial CANFD Interface")
self.tabs.addTab(self.tab2, "Data Visualizer")
self.tab1.layout = QVBoxLayout()
self.tab2.layout = QVBoxLayout()
self.scrollArea = QScrollArea(self.tab1)
self.scrollArea.setWidgetResizable(True)
# self.widget = QWidget()
# self.scrollArea.setWidget(self.widget)
self.layout_SArea = QVBoxLayout(self.scrollArea)
self.layout_SArea.setSpacing(0)
self.tab1.layout.addWidget(self.scrollArea)
self.scrollArea.setSizePolicy(self.mySizePolicy)
self.scrollArea.setStyleSheet("background-color:'#d3f3c8'")
self.layout.addWidget(self.tabs)
self.setLayout(self.layout)
self.qtextbig = QPlainTextEdit()
self.qtextbig.setSizePolicy(self.mySizePolicy)
self.qtextbig.setReadOnly(False)
self.layout_SArea.addWidget(self.qtextbig)
def add_row(self, row):
self.this = str(row)
self.this2 = str(datetime.datetime.now().time())
self.thisthat = self.thisthat + 1
self.qtextbig.appendPlainText(self.this)
self.qtextbig.appendPlainText(self.this2)
self.qtextbig.appendPlainText(str(self.thisthat))
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = FDSerial()
sys.exit(app.exec_())
Here is how the GUI looks right now. The scroll are is way too small! It is in green.
I am looking for the scroll area to take the whole tab size, and then adjust as I adjust the window size. Would appreciate any pointers.
Thanks!
The problem has nothing to do with the QSizePolicy, they are not really necessary. The problem is that you are not using layouts. I think that using the following instruction:
self.tab1.layout = QVBoxLayout()
self.tab2.layout = QVBoxLayout()
add a layout to each tab, but it is only pointing out that there is a new property called layout that takes the value of the QVBoxLayout and that deletes the reference to the layout method of the tab, ie it only deletes the access to the tab1.layout() method, and doing it is a bad practice.
Considering the above I have used the following code:
# ...
class LayoutWidgets(QWidget):
def __init__(self, parent=None):
super(QWidget, self).__init__(parent)
layout = QVBoxLayout(self)
self.thisthat = 0
self.tabs = QTabWidget()
layout.addWidget(self.tabs)
self.tab1 = QWidget()
self.tab2 = QWidget()
self.tabs.addTab(self.tab1, "Serial CANFD Interface")
self.tabs.addTab(self.tab2, "Data Visualizer")
lay = QVBoxLayout(self.tab1)
self.scrollArea = QScrollArea(widgetResizable=True)
self.scrollArea.setStyleSheet("background-color:'#d3f3c8'")
lay.addWidget(self.scrollArea)
layout_SArea = QVBoxLayout(self.scrollArea)
self.qtextbig = QPlainTextEdit(readOnly=False)
layout_SArea.addWidget(self.qtextbig)
def add_row(self, row):
self.this = str(row)
self.this2 = str(datetime.datetime.now().time())
self.thisthat = self.thisthat + 1
self.qtextbig.appendPlainText(self.this)
self.qtextbig.appendPlainText(self.this2)
self.qtextbig.appendPlainText(str(self.thisthat))
# ...

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