Issue
I'm facing the issue that my code works for the first line edit only:
For this I'm using this code:
lineedit = QLineEdit(self)
validator = QIntValidator()
lineedit.setValidator(validator)
layout = QGridLayout()
j = 0
layout.addWidget(QLabel('Tube: '), j+1, 0)
layout.addWidget(lineedit, j+1, 1)
so I thought I could simply use this element / code line for every element of the grid:
lineedit = QLineEdit(self)
validator = QIntValidator()
lineedit.setValidator(validator)
layout = QGridLayout()
j = 0
layout.addWidget(QLabel('Tube: '), j+1, 0)
layout.addWidget(lineedit, j+1, 1)
layout.addWidget(QLabel('Date: '), j+2, 0)
layout.addWidget(QLineEdit(), j+2, 1)
...
but this turns out into:
I could probably rename this button lineedit
into lineedit_j
and count j
up. But is there a smarter way?
Solution
You need to keep separate instances of each of the widgets. I recommend subclassing the QLineEdit to encapsulate the validator.
from PyQt6 import QtWidgets
from PyQt6.QtWidgets import QGridLayout, QLineEdit, QWidget
from PyQt6.QtGui import QIntValidator
import sys
#Subclass QLineEdit to include the Integer Validator
class IntEdit(QLineEdit):
def __init__(self, parent):
super().__init__(parent)
validator = QIntValidator()
self.setValidator(validator)
class Ui(QtWidgets.QMainWindow):
def __init__(self):
super(Ui, self).__init__()
layout = QGridLayout()
# List to hold widgets
self.widgets = []
for w in range(15):
widget = IntEdit(self)
layout.addWidget(widget, w % 5, w % 3)
self.widgets.append(widget)
self.setCentralWidget(QWidget(self))
self.centralWidget().setLayout(layout)
self.show()
app = QtWidgets.QApplication(sys.argv)
window = Ui()
app.exec()
You could also consider using a QTableWidget or QTreeView instead of the grid layout. You could add the custom IntEdit widget to the cell items of those parent controls.
Answered By - stanorama
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.