concatenate three columns into one column pyqt5



  • [0_1558868130767_New Text Document (2).txt](Uploading 100%) hello,,
    I have two issues in pyqt5. here template with two table widgets, first one for extracting data from MySQL (name ,sex, age, city ) (sex=1 or 2 , age = 1 to 6 agegroup and cite by code). Now I want concatenate sex, age and city codes with (day month year) into barcoding column (anther tablewidget_2) according appearing in table widget_1 and result for example should be like this 132612052019 (sex code+age code+city code +date). second issue how can do print for barcode according to result in table widget_2??? we need genius one to solve these issues. please see my file with codes [0_1558868053071_New Text Document (2).txt](Uploading 100%)
    thanks


  • Lifetime Qt Champion

    Hi and welcome to the forums.
    We cant see the "New Text Document (2).txt" uploads.
    Maybe you can paste it here ? ( if its text)



  • import sys
    from PyQt4.QtGui import *

    class TableWidgetDragRows(QTableWidget):
    def init(self, *args, **kwargs):
    super().init(*args, **kwargs)

        self.setDragEnabled(True)
        self.setAcceptDrops(True)
        self.setSelectionBehavior(QAbstractItemView.SelectRows)
        self.setDragDropOverwriteMode(False)
        # self.setSelectionMode(QAbstractItemView.SingleSelection)
    
        self.last_drop_row = None
    
    # Override this method to get the correct row index for insertion
    def dropMimeData(self, row, col, mimeData, action):
        self.last_drop_row = row
        return True
    
    
    def dropEvent(self, event):
        # The QTableWidget from which selected rows will be moved
        sender = event.source()
    
        # Default dropEvent method fires dropMimeData with appropriate parameters (we're interested in the row index).
        super().dropEvent(event)
        # Now we know where to insert selected row(s)
        dropRow = self.last_drop_row
    
        selectedRows = sender.getselectedRowsFast()
    
        # Allocate space for transfer
        for _ in selectedRows:
            self.insertRow(dropRow)
    
        # if sender == receiver (self), after creating new empty rows selected rows might change their locations
        sel_rows_offsets = [0 if self != sender or srow < dropRow else len(selectedRows) for srow in selectedRows]
        selectedRows = [row + offset for row, offset in zip(selectedRows, sel_rows_offsets)]
    
        # copy content of selected rows into empty ones
        for i, srow in enumerate(selectedRows):
            for j in range(self.columnCount()):
                item = sender.item(srow, j)
                if item:
                    source = QTableWidgetItem(item)
                    self.setItem(dropRow + i, j, source)
    
        # delete selected rows
        for srow in reversed(selectedRows):
            sender.removeRow(srow)
    
        event.accept()
    
    
    def getselectedRowsFast(self):
        selectedRows = []
        for item in self.selectedItems():
            if item.row() not in selectedRows:
                selectedRows.append(item.row())
        selectedRows.sort()
        return selectedRows
    

    class Window(QWidget):
    def init(self):
    super().init()

        layout = QHBoxLayout()
        self.setLayout(layout)
    
        self.table_widgets = []
        for _ in range(3):
            tw = TableWidgetDragRows()
            tw.setColumnCount(2)
            tw.setHorizontalHeaderLabels(['Colour', 'Model'])
    
            self.table_widgets.append(tw)
            layout.addWidget(tw)
    
        filled_widget = self.table_widgets[0]
        items = [('Red', 'Toyota'), ('Blue', 'RV'), ('Green', 'Beetle')]
        for i, (colour, model) in enumerate(items):
            c = QTableWidgetItem(colour)
            m = QTableWidgetItem(model)
    
            filled_widget.insertRow(filled_widget.rowCount())
            filled_widget.setItem(i, 0, c)
            filled_widget.setItem(i, 1, m)
    

    if name == 'main':
    app = QApplication(sys.argv)
    window = Window()
    window.show()
    sys.exit(app.exec_())


  • Lifetime Qt Champion

    Hi and welcome to devnet,

    Some things are quite strange. In your original post you are:

    • talking about PyQt5 but in your sample you are using PyQt4
    • talking about MySQL but in your sample there's nothing like that
    • talking about name, sex, age, city but here it looks like unrelated vehicle data
    • talking about joining data but there's nothing related in your sample

    Are you sure you are showing the correct code ?



  • @SGaist sorry ,I did mistake, I attached wrong file . here is right file :

    from PyQt5 import QtCore, QtGui, QtWidgets
    import pymysql
    import random

    class Ui_MainWindow(object):
    def init(self):
    self.conn = pymysql.connect(host="localhost", user="root", password="", database="badr")
    self.mycur = self.conn.cursor()

    def loaddata(self):
        sex = self.lineEdit.text()
        age = self.lineEdit_2.text()
        city = self.lineEdit_3.text()
    
        result = self.mycur.execute("SELECT * FROM example WHERE age = '%s' AND city = '%s' " % (''.join(age), ''.join(city)))
        res = self.mycur.fetchall()
    
        self.tableWidget.setRowCount(0)
        for row_number, row_data in enumerate(res):
            self.tableWidget.insertRow(row_number)
            for column_number, data in enumerate(row_data):
                self.tableWidget.setItem(row_number, column_number, QtWidgets.QTableWidgetItem(str(data)))
        return
        self.conn.close()
    
    def showmessagebox(self, title, message):
        mesgbox = QtGui.QMessageBox()
        mesgbox.seticon(QtGui.QMessageBox.Warning)
        mesgbox.setWindowTitle(title)
        mesgbox.setText(message)
        mesgbox.setStandardButtons(QtGui.QMessageBox.OK)
        mesgbox.exec()
    
    def search(self):
        name_1 = self.lineEdit_5.text()
        result_1 = self.mycur.execute("SELECT * FROM example WHERE name='%s' " % (''.join(name_1)))
        res_1 = self.mycur.fetchall()
    
        self.tableWidget.setRowCount(0)
        for row_number, row_data in enumerate(res_1):
            self.tableWidget.insertRow(row_number)
            for column_number, data in enumerate(row_data):
                self.tableWidget.setItem(row_number, column_number, QtWidgets.QTableWidgetItem(str(data)))
        return
        self.conn.close()
    
    def randdata(self):
        rand_1 = self.lineEdit_4.text()
        age = self.lineEdit_2.text()
        city = self.lineEdit_3.text()
    
        result_2 = self.mycur.execute( "SELECT * FROM example WHERE age = '%s' AND city = '%s' " % (''.join(age), ''.join(city)))
        res_2 = self.mycur.fetchall()
    
        random_2 = random.sample(res_2, k=int(rand_1))
    
        self.tableWidget.setRowCount(0)
        for row_number, row_data in enumerate(random_2):
            self.tableWidget.insertRow(row_number)
            for column_number, data in enumerate(row_data):
                self.tableWidget.setItem(row_number, column_number, QtWidgets.QTableWidgetItem(str(data)))
    
        return
        self.conn.close()
    
    
          
    
    
    
    
    
          
    
    
    
    
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(1312, 852)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.tableWidget = QtWidgets.QTableWidget(self.centralwidget)
        self.tableWidget.setGeometry(QtCore.QRect(30, 150, 821, 401))
        self.tableWidget.setObjectName("tableWidget")
        self.tableWidget.setColumnCount(7)
        self.tableWidget.setRowCount(0)
        item = QtWidgets.QTableWidgetItem()
        self.tableWidget.setHorizontalHeaderItem(0, item)
        item = QtWidgets.QTableWidgetItem()
        self.tableWidget.setHorizontalHeaderItem(1, item)
        item = QtWidgets.QTableWidgetItem()
        self.tableWidget.setHorizontalHeaderItem(2, item)
        item = QtWidgets.QTableWidgetItem()
        self.tableWidget.setHorizontalHeaderItem(3, item)
        item = QtWidgets.QTableWidgetItem()
        self.tableWidget.setHorizontalHeaderItem(4, item)
        item = QtWidgets.QTableWidgetItem()
        self.tableWidget.setHorizontalHeaderItem(5, item)
        item = QtWidgets.QTableWidgetItem()
        self.tableWidget.setHorizontalHeaderItem(6, item)
        self.lineEdit = QtWidgets.QLineEdit(self.centralwidget)
        self.lineEdit.setGeometry(QtCore.QRect(20, 80, 171, 41))
        self.lineEdit.setObjectName("lineEdit")
        self.lineEdit_2 = QtWidgets.QLineEdit(self.centralwidget)
        self.lineEdit_2.setGeometry(QtCore.QRect(210, 80, 101, 41))
        self.lineEdit_2.setObjectName("lineEdit_2")
        self.lineEdit_3 = QtWidgets.QLineEdit(self.centralwidget)
        self.lineEdit_3.setGeometry(QtCore.QRect(320, 80, 113, 41))
        self.lineEdit_3.setObjectName("lineEdit_3")
        self.label = QtWidgets.QLabel(self.centralwidget)
        self.label.setGeometry(QtCore.QRect(70, 50, 68, 19))
        self.label.setObjectName("label")
        self.label_2 = QtWidgets.QLabel(self.centralwidget)
        self.label_2.setGeometry(QtCore.QRect(210, 50, 68, 19))
        self.label_2.setObjectName("label_2")
        self.label_3 = QtWidgets.QLabel(self.centralwidget)
        self.label_3.setGeometry(QtCore.QRect(330, 50, 68, 19))
        self.label_3.setObjectName("label_3")
        self.lineEdit_4 = QtWidgets.QLineEdit(self.centralwidget)
        self.lineEdit_4.setGeometry(QtCore.QRect(440, 80, 113, 41))
        self.lineEdit_4.setObjectName("lineEdit_4")
        self.label_4 = QtWidgets.QLabel(self.centralwidget)
        self.label_4.setGeometry(QtCore.QRect(440, 18, 191, 51))
        self.label_4.setObjectName("label_4")
        self.pushButton = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton.setGeometry(QtCore.QRect(110, 10, 121, 41))
        self.pushButton.setObjectName("pushButton")
        self.pushButton.clicked.connect(self.loaddata)
        self.label_5 = QtWidgets.QLabel(self.centralwidget)
        self.label_5.setGeometry(QtCore.QRect(757, 40, 161, 41))
        self.label_5.setObjectName("label_5")
        self.lineEdit_5 = QtWidgets.QLineEdit(self.centralwidget)
        self.lineEdit_5.setGeometry(QtCore.QRect(750, 80, 181, 41))
        self.lineEdit_5.setObjectName("lineEdit_5")
        self.pushButton_2 = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton_2.setGeometry(QtCore.QRect(80, 590, 161, 41))
        self.pushButton_2.setObjectName("pushButton_2")
        self.pushButton_3 = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton_3.setGeometry(QtCore.QRect(290, 590, 211, 41))
        self.pushButton_3.setObjectName("pushButton_3")
        self.listWidget = QtWidgets.QListWidget(self.centralwidget)
        self.listWidget.setGeometry(QtCore.QRect(860, 150, 191, 401))
        self.listWidget.setObjectName("listWidget")
        self.tableWidget_2 = QtWidgets.QTableWidget(self.centralwidget)
        self.tableWidget_2.setGeometry(QtCore.QRect(1060, 150, 256, 401))
        self.tableWidget_2.setObjectName("tableWidget_2")
        self.tableWidget_2.setColumnCount(1)
        self.tableWidget_2.setRowCount(0)
        item = QtWidgets.QTableWidgetItem()
        self.tableWidget_2.setHorizontalHeaderItem(0, item)
        self.graphicsView = QtWidgets.QGraphicsView(self.centralwidget)
        self.graphicsView.setGeometry(QtCore.QRect(520, 600, 761, 192))
        self.graphicsView.setObjectName("graphicsView")
        self.calendarWidget = QtWidgets.QCalendarWidget(self.centralwidget)
        self.calendarWidget.setGeometry(QtCore.QRect(30, 650, 448, 289))
        self.calendarWidget.setObjectName("calendarWidget")
        self.dateEdit = QtWidgets.QDateEdit(self.centralwidget)
        self.dateEdit.setGeometry(QtCore.QRect(1030, 30, 171, 41))
        self.dateEdit.setObjectName("dateEdit")
        self.pushButton_4 = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton_4.setGeometry(QtCore.QRect(640, 560, 112, 34))
        self.pushButton_4.setObjectName("pushButton_4")
        self.pushButton_4.clicked.connect(self.adding)
        self.pushButton_5 = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton_5.setGeometry(QtCore.QRect(820, 560, 112, 34))
        self.pushButton_5.setObjectName("pushButton_5")
        self.pushButton_6 = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton_6.setGeometry(QtCore.QRect(940, 80, 112, 34))
        self.pushButton_6.setObjectName("pushButton_6")
        self.pushButton_6.clicked.connect(self.search)
        self.pushButton_7 = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton_7.setGeometry(QtCore.QRect(560, 80, 112, 34))
        self.pushButton_7.setObjectName("pushButton_7")
        self.pushButton_7.clicked.connect(self.randdata)
        MainWindow.setCentralWidget(self.centralwidget)
        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"))
        item = self.tableWidget.horizontalHeaderItem(0)
        item.setText(_translate("MainWindow", "Name"))
        item = self.tableWidget.horizontalHeaderItem(1)
        item.setText(_translate("MainWindow", "Sex"))
        item = self.tableWidget.horizontalHeaderItem(2)
        item.setText(_translate("MainWindow", "Age"))
        item = self.tableWidget.horizontalHeaderItem(3)
        item.setText(_translate("MainWindow", "City"))
        item = self.tableWidget.horizontalHeaderItem(4)
        item.setText(_translate("MainWindow", "barcode(of item)"))
        item = self.tableWidget.horizontalHeaderItem(5)
        item.setText(_translate("MainWindow", "lat"))
        item = self.tableWidget.horizontalHeaderItem(6)
        item.setText(_translate("MainWindow", "long"))
        self.label.setText(_translate("MainWindow", "Sex"))
        self.label_2.setText(_translate("MainWindow", "Age"))
        self.label_3.setText(_translate("MainWindow", "City"))
        self.label_4.setText(_translate("MainWindow", "No of sample random"))
        self.pushButton.setText(_translate("MainWindow", "Run"))
        self.label_5.setText(_translate("MainWindow", "Search by name"))
        self.pushButton_2.setText(_translate("MainWindow", "print barcode"))
        self.pushButton_3.setText(_translate("MainWindow", "export file(cvs file)"))
        item = self.tableWidget_2.horizontalHeaderItem(0)
        item.setText(_translate("MainWindow", "barcodeing"))
        self.pushButton_4.setText(_translate("MainWindow", "map"))
        self.pushButton_5.setText(_translate("MainWindow", "edit data"))
        self.pushButton_6.setText(_translate("MainWindow", "search"))
        self.pushButton_7.setText(_translate("MainWindow", "random"))
    

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



  • @badr
    You have one table widget (or similar, actually presumably QTableView rather than QTableWidget since you have your own model) holding rows & columns from a SQL query. You say you want another table widget to show a column "computed" (at client side) from columns in the first one.

    So why not create a second model whose data() method is overridden to perform the necessary computation and return the desired final string for Qt::DisplayRole using the index.row/column() (not just the index) as indexers into the SQL model's rows/columns?

    Or, if you want to stick with your current usage of QTableWidget (not ideal that you use Python SQL calls and copy result set into that, but up to you), you could make your second one a QTableWidget too and use setData() to populate its rows/columns with the actual corresponding strings whenever the first one changes (more work depending on how often your data changes, but in your case it might only be during loaddata() when you populate if it does not change thereafter).