I have a pyqt application and when using the same instance of the QLabel class on the gridlayout it is not working. I see only one instance being displayed.
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QToolTip, QPushButton, QMessageBox, QAction, qApp, QMenu, QTextEdit, QToolBar, QMdiArea, QGridLayout, QLabel, QDialog
from PyQt5.QtGui import QFont, QIcon, QPainter, QVector2D
from PyQt5.Qt import QDesktopWidget, QMainWindow, Qt, QHBoxLayout, QVBoxLayout,\
QLineEdit
from PyQt5.QtCore import QPoint
class Example(QDialog):
count = 0
def __init__(self, *args, **kwargs):
super(Example, self).__init__(*args, **kwargs)
self.initUI()
def initUI(self):
grid = QGridLayout()
a1 = QLabel('alphanumeric characters')
a2 = QLabel('alphanumeric characters')
grid.addWidget(QLabel('Name'), 1, 0)
grid.addWidget(QLineEdit(), 1, 1)
grid.addWidget(QLabel('only alphanumeric'), 1, 2)
grid.addWidget(QLabel('Street1'), 2, 0)
grid.addWidget(QLineEdit(), 2, 1)
grid.addWidget(QLabel('only alphanumeric'), 2, 2)
grid.addWidget(QLabel('Street2'), 3, 0)
grid.addWidget(QLineEdit(), 3, 1)
grid.addWidget(QLabel('only alphanumeric'), 3, 2)
grid.addWidget(QLabel('City'), 3, 0)
grid.addWidget(QLineEdit(), 3, 1)
grid.addWidget(QLabel('only alphanumeric'), 3, 2)
self.setLayout(grid)
self.setGeometry(500, 500, 500, 500)
self.setWindowTitle('Lines')
self.show()
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = Example()
# ex.show()
sys.exit(app.exec_())
First the coordinates start from (0, 0), so that part I have corrected.
Going to the problem, you do not have to add one to one, the addWidget()
method is overloaded, so there is a 4 and 5 argument that indicates the span in the row and column, respectively.
void addWidget(QWidget *widget, int row, int column, Qt::Alignment alignment = ...)
void addWidget(QWidget *widget, int fromRow, int fromColumn, int rowSpan, int columnSpan, Qt::Alignment alignment = ...)
import sys
from PyQt5.QtWidgets import QApplication, QDialog, QGridLayout, QLabel, QLineEdit
class Example(QDialog):
def __init__(self, *args, **kwargs):
super(Example, self).__init__(*args, **kwargs)
self.initUI()
def initUI(self):
grid = QGridLayout(self)
a1 = QLabel('alphanumeric characters')
a2 = QLabel('alphanumeric characters')
grid.addWidget(QLabel('Name'), 0, 0)
grid.addWidget(QLineEdit(), 0, 1)
grid.addWidget(QLabel('Street1'), 1, 0)
grid.addWidget(QLineEdit(), 1, 1)
grid.addWidget(QLabel('Street2'), 2, 0)
grid.addWidget(QLineEdit(), 2, 1)
grid.addWidget(QLabel('City'), 3, 0)
grid.addWidget(QLineEdit(), 3, 1)
grid.addWidget(QLabel('only alphanumeric'), 0, 2, 4, 1)
self.setGeometry(500, 500, 500, 500)
self.setWindowTitle('Lines')
self.show()
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = Example()
# ex.show()
sys.exit(app.exec_())