I am developing an application using PyQt4 and Qt4Designer, I have designed from designer and generated python code. As you can see in the below image, when I am adding first row, it's occupying whole layout space, but later rows are of fixed width.
Image showing the actual problem
Here's my code...
main.py
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'pyqt.ui'
#
# Created by: PyQt4 UI code generator 4.11.4
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
def _fromUtf8(s):
return s
try:
_encoding = QtGui.QApplication.UnicodeUTF8
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig)
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName(_fromUtf8("MainWindow"))
MainWindow.resize(983, 600)
MainWindow.setMinimumSize(QtCore.QSize(900, 600))
self.centralwidget = QtGui.QWidget(MainWindow)
self.centralwidget.setObjectName(_fromUtf8("centralwidget"))
self.gridLayoutWidget = QtGui.QWidget(self.centralwidget)
self.gridLayoutWidget.setGeometry(QtCore.QRect(100, 90, 675, 441))
self.gridLayoutWidget.setObjectName(_fromUtf8("gridLayoutWidget"))
self.gridLayout = QtGui.QGridLayout(self.gridLayoutWidget)
self.gridLayout.setContentsMargins(0, -1, -1, -1)
self.gridLayout.setObjectName(_fromUtf8("gridLayout"))
self.tableWidget = QtGui.QTableWidget(self.gridLayoutWidget)
self.tableWidget.setMinimumSize(QtCore.QSize(589, 439))
self.tableWidget.setObjectName(_fromUtf8("tableWidget"))
self.tableWidget.setColumnCount(4)
self.tableWidget.setRowCount(0)
item = QtGui.QTableWidgetItem()
self.tableWidget.setHorizontalHeaderItem(0, item)
item = QtGui.QTableWidgetItem()
self.tableWidget.setHorizontalHeaderItem(1, item)
item = QtGui.QTableWidgetItem()
self.tableWidget.setHorizontalHeaderItem(2, item)
item = QtGui.QTableWidgetItem()
self.tableWidget.setHorizontalHeaderItem(3, item)
self.tableWidget.horizontalHeader().setCascadingSectionResizes(False)
self.tableWidget.verticalHeader().setStretchLastSection(True)
self.gridLayout.addWidget(self.tableWidget, 0, 0, 1, 1)
self.label = QtGui.QLabel(self.centralwidget)
self.label.setGeometry(QtCore.QRect(100, 20, 85, 27))
self.label.setObjectName(_fromUtf8("label"))
self.AddTask = QtGui.QPushButton(self.centralwidget)
self.AddTask.setGeometry(QtCore.QRect(610, 20, 85, 27))
self.AddTask.setObjectName(_fromUtf8("AddTask"))
self.gridLayoutWidget.raise_()
self.label.raise_()
self.AddTask.raise_()
self.tableWidget.raise_()
MainWindow.setCentralWidget(self.centralwidget)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
MainWindow.setWindowTitle(_translate("MainWindow", "Stockroom Adidas", None))
self.tableWidget.setToolTip(_translate("MainWindow", "<html><head/><body><p>This is where you can add new jobs</p></body></html>", None))
item = self.tableWidget.horizontalHeaderItem(0)
item.setText(_translate("MainWindow", "Name", None))
item = self.tableWidget.horizontalHeaderItem(1)
item.setText(_translate("MainWindow", "SKU", None))
item = self.tableWidget.horizontalHeaderItem(2)
item.setText(_translate("MainWindow", "Size", None))
item = self.tableWidget.horizontalHeaderItem(3)
item.setText(_translate("MainWindow", "Status", None))
self.label.setText(_translate("MainWindow", "<html><head/><body><p><span style=\" font-size:14pt;\">Lobby</span></p></body></html>", None))
self.AddTask.setText(_translate("MainWindow", "Add Task", None))
app.py
from PyQt4.QtCore import QRegExp
from PyQt4.QtGui import QHeaderView
from PyQt4.QtGui import QTableWidgetItem
from main import Ui_MainWindow, QtCore, QtGui
import sys
from newtask import Ui_NewTask
class MainWindow(QtGui.QMainWindow, Ui_MainWindow):
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
resolution = QtGui.QDesktopWidget().screenGeometry()
# positioning window to center
self.move((resolution.width() / 2) - (self.frameSize().width() / 2),
(resolution.height() / 2) - (self.frameSize().height() / 2))
self.setupUi(self)
# Customizing Columns in Table
rowHeader = self.tableWidget.horizontalHeader()
rowHeader.setResizeMode(0, QHeaderView.ResizeToContents)
rowHeader.setResizeMode(1, QHeaderView.Stretch)
rowHeader.setResizeMode(2, QHeaderView.Stretch)
rowHeader.setResizeMode(3, QHeaderView.ResizeToContents)
# self.tableWidget.resizeColumnsToContents()
# self.tableWidget.resizeRowsToContents()
# When clicked on Add Task button
def showDialog():
newdialog = NewTask(parent=self)
newdialog.show()
if newdialog.exec_():
# adding rows to the table
for i in range(len(newdialog.data)):
currentrow = self.tableWidget.rowCount()
self.tableWidget.insertRow(currentrow)
for j in range(len(newdialog.data[i])):
self.tableWidget.setItem(currentrow, j, newdialog.data[i][j])
self.AddTask.clicked.connect(showDialog)
header = self.tableWidget.verticalHeader()
header.setResizeMode(0, QHeaderView.Stretch)
# header.setDefaultSectionSize(12)
I have another class which inherits QDialog which has lot code, don't want to make this complex, not posting it... you can seee that when the AddTask button is clicked I am connecting the signal to showDialog function. There I am adding rows, I don't know where I am doing wrong, I have tried all the below possible ways.
self.tableWidget.resizeColumnsToContents()
self.tableWidget.resizeRowsToContents()
OR
header.setResizeMode(QHeaderView.Stretch)
OR
header.setResizeMode(QHeaderView.Fixed)
OR
self.tableWidget.rowHeight(20)
OR
self.tableWidget.resizeColumnsToContents()
self.tableWidget.resizeRowsToContents()
None of them worked... Please help...
EDIT1:
When I try to add rows in qtdesigner, facing the same problem, attaching the image here
QtDesigner
May be self.tableWidget.verticalHeader().setStretchLastSection(True) is causing problem.
Related
I'm pretty new to python and especially to pyqt4 but I would like to learn it right.
Therefore I want to build my new learning project in three different files.
One main.py file in which I call everything. One by the QDesigner generated UI file (Main_Ui.py) and one Main_Functions.py file in which I would like to keep all my functions.
My first question would therefore be whether this is a "good programming style" or should I do it in a different way?
During the implementation of my idea I got stuck with calling the function. The console says "TypeError: connect() slot argument should be a callable or a signal, not 'NoneType'".
Could you please help me and tell me what I did wrong as I googled now nearly all day long and I could not find anything that would fit or I didn't understood it. It would be really great and would help me a lot learning how to do it right :)
Thank you very much :)
Here is my examplary code so far:
Main.py
import sys
from PyQt4 import QtGui, QtCore
from Main_Ui import Ui_MainWindow
import Main_Functions as f
class MainWindow(QtGui.QMainWindow):
def __init__(self, parent=None):
QtGui.QWidget.__init__(self, parent)
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
self.ui.btn1.clicked.connect(f.download(self.ui))
if __name__ == "__main__":
app = QtGui.QApplication(sys.argv)
myapp = MainWindow()
myapp.show()
sys.exit(app.exec_())
Main_Functions.py
def download(window):
window.completed = 0
while window.completed < 100:
window.completed += 0.0001
window.progress.setValue(window.completed)
And the probably not so interesting Main_Ui.py
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'Main.ui'
#
# Created by: PyQt4 UI code generator 4.11.4
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
def _fromUtf8(s):
return s
try:
_encoding = QtGui.QApplication.UnicodeUTF8
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig)
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName(_fromUtf8("MainWindow"))
MainWindow.resize(1000, 848)
self.centralwidget = QtGui.QWidget(MainWindow)
self.centralwidget.setObjectName(_fromUtf8("centralwidget"))
self.gridLayoutWidget = QtGui.QWidget(self.centralwidget)
self.gridLayoutWidget.setGeometry(QtCore.QRect(210, 150, 2, 2))
self.gridLayoutWidget.setObjectName(_fromUtf8("gridLayoutWidget"))
self.gridLayout = QtGui.QGridLayout(self.gridLayoutWidget)
self.gridLayout.setObjectName(_fromUtf8("gridLayout"))
self.tableWidget = QtGui.QTableWidget(self.centralwidget)
self.tableWidget.setGeometry(QtCore.QRect(50, 120, 256, 192))
self.tableWidget.setObjectName(_fromUtf8("tableWidget"))
self.tableWidget.setColumnCount(1)
self.tableWidget.setRowCount(1)
item = QtGui.QTableWidgetItem()
self.tableWidget.setVerticalHeaderItem(0, item)
item = QtGui.QTableWidgetItem()
self.tableWidget.setHorizontalHeaderItem(0, item)
self.progress = QtGui.QProgressBar(self.centralwidget)
self.progress.setGeometry(QtCore.QRect(180, 550, 118, 23))
self.progress.setProperty("value", 24)
self.progress.setObjectName(_fromUtf8("progress"))
self.btn1 = QtGui.QPushButton(self.centralwidget)
self.btn1.setGeometry(QtCore.QRect(490, 200, 75, 23))
self.btn1.setObjectName(_fromUtf8("btn1"))
self.lbl1 = QtGui.QLabel(self.centralwidget)
self.lbl1.setGeometry(QtCore.QRect(400, 200, 46, 13))
self.lbl1.setObjectName(_fromUtf8("lbl1"))
self.txt1 = QtGui.QLineEdit(self.centralwidget)
self.txt1.setGeometry(QtCore.QRect(330, 160, 113, 20))
self.txt1.setObjectName(_fromUtf8("txt1"))
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtGui.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 1000, 21))
self.menubar.setObjectName(_fromUtf8("menubar"))
self.menuDatei = QtGui.QMenu(self.menubar)
self.menuDatei.setObjectName(_fromUtf8("menuDatei"))
MainWindow.setMenuBar(self.menubar)
self.statusbar = QtGui.QStatusBar(MainWindow)
self.statusbar.setObjectName(_fromUtf8("statusbar"))
MainWindow.setStatusBar(self.statusbar)
self.actionSchlie_en = QtGui.QAction(MainWindow)
self.actionSchlie_en.setObjectName(_fromUtf8("actionSchlie_en"))
self.menuDatei.addAction(self.actionSchlie_en)
self.menubar.addAction(self.menuDatei.menuAction())
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow", None))
item = self.tableWidget.verticalHeaderItem(0)
item.setText(_translate("MainWindow", "T", None))
item = self.tableWidget.horizontalHeaderItem(0)
item.setText(_translate("MainWindow", "1", None))
self.btn1.setText(_translate("MainWindow", "PushButton", None))
self.lbl1.setText(_translate("MainWindow", "TextLabel", None))
self.menuDatei.setTitle(_translate("MainWindow", "Datei", None))
self.actionSchlie_en.setText(_translate("MainWindow", "Schließen", None))
if __name__ == "__main__":
import sys
app = QtGui.QApplication(sys.argv)
MainWindow = QtGui.QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
MainWindow.show()
sys.exit(app.exec_())
The problem is your connection
self.ui.btn1.clicked.connect(f.download(self.ui))
You need to pass a callback to the connect function. Here, you're actually calling the download function (which returns None) and passing the results to connect.
You need to do this instead
self.ui.btn1.clicked.connect(lambda: f.download(self.ui))
It does often make sense to separate non-gui business logic out into separate modules. This allows them to be re-used in other modules and GUI's. However, in your case, you're performing GUI modification in code outside your GUI class. That's generally not a very good design and it would be better for you to define those functions inside your MainWindow class.
Reading data in from a simple dict d={key:['desc',dateadded]}
Goal is to add data into table view and sort by date in the list. Cannot get any data to add when trying to put table on main window.
The issue lies with how I am placing the table on the main window. I have a working widget with table and am now trying to combine the two files. Currently the application crashes. Dont want you to write the code but a nudge in the right direction would be a big help.
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'display.ui'
#
# Created by: PyQt4 UI code generator 4.11.4
#
# WARNING! All changes made in this file will be lost!
from PyQt4.QtGui import (QMainWindow, QApplication)
from PyQt4 import QtCore, QtGui
from PyQt4.QtCore import *
from PyQt4.QtGui import *
import sys
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
def _fromUtf8(s):
return s
try:
_encoding = QtGui.QApplication.UnicodeUTF8
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig)
class Ui_MainWindow(object):
def __init__(self):
#app = QApplication(sys.argv)
self.window = QMainWindow()
self.setupUi(self.window)
self.window.show()
self.setmydata()
def setupUi(self, MainWindow):
MainWindow.setObjectName(_fromUtf8("MainWindow"))
MainWindow.resize(296, 478)
MainWindow.setIconSize(QtCore.QSize(0, 0))
MainWindow.setAnimated(False)
MainWindow.setTabShape(QtGui.QTabWidget.Rounded)
self.centralwidget = QtGui.QWidget(MainWindow)
self.centralwidget.setObjectName(_fromUtf8("centralwidget"))
self.tableView = QtGui.QTableView(self.centralwidget)
self.tableView.setGeometry(QtCore.QRect(20, 50, 261, 391))
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Expanding)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.tableView.sizePolicy().hasHeightForWidth())
self.tableView.setSizePolicy(sizePolicy)
self.tableView.setEditTriggers(QtGui.QAbstractItemView.AllEditTriggers)
self.tableView.setDragEnabled(True)
self.tableView.setAlternatingRowColors(True)
self.tableView.setSelectionMode(QtGui.QAbstractItemView.MultiSelection)
self.tableView.setSortingEnabled(False)
self.tableView.setObjectName(_fromUtf8("tableView"))
self.pushButton = QtGui.QPushButton(self.centralwidget)
self.pushButton.setGeometry(QtCore.QRect(20, 10, 121, 31))
self.pushButton.setObjectName(_fromUtf8("pushButton"))
self.pushButton_2 = QtGui.QPushButton(self.centralwidget)
self.pushButton_2.setGeometry(QtCore.QRect(160, 10, 121, 31))
self.pushButton_2.setObjectName(_fromUtf8("pushButton_2"))
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtGui.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 296, 21))
self.menubar.setObjectName(_fromUtf8("menubar"))
MainWindow.setMenuBar(self.menubar)
self.statusbar = QtGui.QStatusBar(MainWindow)
self.statusbar.setObjectName(_fromUtf8("statusbar"))
MainWindow.setStatusBar(self.statusbar)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def setmydata(self):
d={"12345678":["do some stuff here that needs to be in a large cell to wrap text","1"],"12343378":["do stuff","1"]}
self.data = {}
keys=d.keys()
self.data['col1']=keys
self.data['col2']=[]
for key in keys:
self.data['col2'].append(d[key][0])
horHeaders = []
for n, key in enumerate(sorted(self.data.keys())):
horHeaders.append(key)
for m, item in enumerate(self.data[key]):
newitem = QTableWidgetItem(item)
self.setItem(m, n, newitem)
self.setHorizontalHeaderLabels(horHeaders)
def retranslateUi(self, MainWindow):
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow", None))
self.pushButton.setText(_translate("MainWindow", "Add New", None))
self.pushButton_2.setText(_translate("MainWindow", "Save", None))
app = QApplication(sys.argv)
frame = Ui_MainWindow()
#frame.show()
app.exec_()
After digging through the code I found line
self.tableView = QtGui.QTableView(self.centralwidget)
needed to be QTableWidget rather than a View. This allows for me to set values and so on.
I am trying to write a small app and want to somehow "catch" the row numbers of when a row is dragged / dropped but with no effect on the table. I have created two files, the first is a MainWindow UI file created in Qt Designer for the basic GUI and the second has the code to layout the QTableWidget with some data.
It works as I want, that is to say it shows a drag and drop movement to the user, but changes nothing when dropped. I have read other posts, but they all seem to be wanting to move the data, so they haven't been of any help with this.
UiFile.py
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'UiFile.ui'
#
# Created: Thu Apr 7 21:07:11 2016
# by: PyQt4 UI code generator 4.11.2
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
def _fromUtf8(s):
return s
try:
_encoding = QtGui.QApplication.UnicodeUTF8
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig)
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName(_fromUtf8("MainWindow"))
MainWindow.resize(763, 269)
self.centralwidget = QtGui.QWidget(MainWindow)
self.centralwidget.setObjectName(_fromUtf8("centralwidget"))
self.gridLayout = QtGui.QGridLayout(self.centralwidget)
self.gridLayout.setObjectName(_fromUtf8("gridLayout"))
self.tableWidget = QtGui.QTableWidget(self.centralwidget)
self.tableWidget.setDragEnabled(False)
self.tableWidget.setDragDropOverwriteMode(False)
self.tableWidget.setDragDropMode(QtGui.QAbstractItemView.DragDrop)
self.tableWidget.setDefaultDropAction(QtCore.Qt.ActionMask)
self.tableWidget.setSelectionMode(QtGui.QAbstractItemView.SingleSelection)
self.tableWidget.setSelectionBehavior(QtGui.QAbstractItemView.SelectRows)
self.tableWidget.setObjectName(_fromUtf8("tableWidget"))
self.tableWidget.setColumnCount(7)
self.tableWidget.setRowCount(0)
item = QtGui.QTableWidgetItem()
self.tableWidget.setHorizontalHeaderItem(0, item)
item = QtGui.QTableWidgetItem()
self.tableWidget.setHorizontalHeaderItem(1, item)
item = QtGui.QTableWidgetItem()
self.tableWidget.setHorizontalHeaderItem(2, item)
item = QtGui.QTableWidgetItem()
self.tableWidget.setHorizontalHeaderItem(3, item)
item = QtGui.QTableWidgetItem()
self.tableWidget.setHorizontalHeaderItem(4, item)
item = QtGui.QTableWidgetItem()
self.tableWidget.setHorizontalHeaderItem(5, item)
item = QtGui.QTableWidgetItem()
self.tableWidget.setHorizontalHeaderItem(6, item)
self.gridLayout.addWidget(self.tableWidget, 0, 0, 1, 1)
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtGui.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 763, 24))
self.menubar.setObjectName(_fromUtf8("menubar"))
MainWindow.setMenuBar(self.menubar)
self.statusbar = QtGui.QStatusBar(MainWindow)
self.statusbar.setObjectName(_fromUtf8("statusbar"))
MainWindow.setStatusBar(self.statusbar)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow", None))
item = self.tableWidget.horizontalHeaderItem(0)
item.setText(_translate("MainWindow", "Column 1", None))
item = self.tableWidget.horizontalHeaderItem(1)
item.setText(_translate("MainWindow", "Column 2", None))
item = self.tableWidget.horizontalHeaderItem(2)
item.setText(_translate("MainWindow", "Column 3", None))
item = self.tableWidget.horizontalHeaderItem(3)
item.setText(_translate("MainWindow", "Column 4", None))
item = self.tableWidget.horizontalHeaderItem(4)
item.setText(_translate("MainWindow", "Column 5", None))
item = self.tableWidget.horizontalHeaderItem(5)
item.setText(_translate("MainWindow", "New Column", None))
item = self.tableWidget.horizontalHeaderItem(6)
item.setText(_translate("MainWindow", "Column 7", None))
main.py
#!/usr/bin/env python
import sys
from PyQt4 import QtGui
import UiFile
class ExampleApp(QtGui.QMainWindow, UiFile.Ui_MainWindow):
def __init__(self, parent=None):
super(ExampleApp, self).__init__(parent)
self.setupUi(self)
self.home()
def home(self):
self.tableWidget.itemChanged.connect(self.my_item_changed_info)
self.add_row_to_ml_table("R1C1", "R1C2", "R1C3", "R1C4", "R1C5", "R1C6", "R1C7")
self.add_row_to_ml_table("R2C1", "R2C2", "R2C3", "R2C4", "R2C5", "R2C6", "R2C7")
self.add_row_to_ml_table("R3C1", "R3C2", "R3C3", "R3C4", "R3C5", "R3C6", "R3C7")
self.add_row_to_ml_table("R4C1", "R4C2", "R4C3", "R4C4", "R4C5", "R4C6", "R4C7")
self.add_row_to_ml_table("R5C1", "R5C2", "R5C3", "R5C4", "R5C5", "R5C6", "R5C7")
self.add_row_to_ml_table("R6C1", "R6C2", "R6C3", "R6C4", "R6C5", "R6C6", "R6C7")
self.add_row_to_ml_table("R7C1", "R7C2", "R7C3", "R7C4", "R7C5", "R7C6", "R7C7")
def add_row_to_ml_table(self, c1, c2, c3, c4, c5, c6, c7):
rowposition = self.tableWidget.rowCount()
self.tableWidget.insertRow(rowposition)
self.tableWidget.setItem(rowposition, 0, QtGui.QTableWidgetItem(c1))
self.tableWidget.setItem(rowposition, 1, QtGui.QTableWidgetItem(c2))
self.tableWidget.setItem(rowposition, 2, QtGui.QTableWidgetItem(c3))
self.tableWidget.setItem(rowposition, 3, QtGui.QTableWidgetItem(c4))
self.tableWidget.setItem(rowposition, 4, QtGui.QTableWidgetItem(c5))
self.tableWidget.setItem(rowposition, 5, QtGui.QTableWidgetItem(c6))
self.tableWidget.setItem(rowposition, 6, QtGui.QTableWidgetItem(c7))
def my_item_changed_info(self, something):
if self.tableWidget.currentRow() != -1:
print("current", self.tableWidget.currentRow(), self.tableWidget.currentColumn())
print(something.row(), something.column())
def closeEvent(self, event):
choice = QtGui.QMessageBox.question(self, 'Xmms2 Skin', 'Do you want to quit the applictaion?', QtGui.QMessageBox.Yes | QtGui.QMessageBox.No)
if choice == QtGui.QMessageBox.Yes:
event.accept()
else:
event.ignore()
def main():
app = QtGui.QApplication(sys.argv)
form = ExampleApp()
form.show()
app.exec_()
if __name__ == '__main__':
main()
So what I need to do is get the information of the row that has been dragged and the row that is being dropped onto.
From what I have read on this I would have to create a sub-Class of the QTableWidget in order to catch the event.
Can I do that using Qt Designer? I picked this in the first place according to my programming skills, and this is a small fragment of a much more complex GUI layout.
I solved it myself by adding
self.tableWidget.__class__.dropEvent = self.testdropfunc
into the home function, and then the testdropfunc looks like this :-
def testdropfunc(self, event):
moved_from = self.tableWidget.currentRow()
moved_to = self.tableWidget.rowAt(event.pos().y())
print("Drop from " + str(moved_from) + " into row " + str(moved_to))
event.accept()
I do realise that this does not actually move anything as all I wanted was the row information for the item ("dragged from" and "dropped to")
I have a list of data which is shown in the Qcombobox (using 'addItems')
Now - if the list is changed by loading data from a file with pushbutton - i don't see the new data in the combobx.
The new data is there (I can print it after loading)
What do I miss?
below is the code for the simplified gui
from PyQt4 import QtCore, QtGui
from PyQt4.QtGui import QFileDialog
import pandas as pd
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
def _fromUtf8(s):
return s
try:
_encoding = QtGui.QApplication.UnicodeUTF8
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig)
class Ui_MainWindow(object):
def __init__(self):
self.comboData=['None']
def setupUi(self, MainWindow):
MainWindow.setObjectName(_fromUtf8("MainWindow"))
MainWindow.resize(456, 172)
self.centralwidget = QtGui.QWidget(MainWindow)
self.centralwidget.setObjectName(_fromUtf8("centralwidget"))
self.comboBox = QtGui.QComboBox(self.centralwidget)
self.comboBox.setGeometry(QtCore.QRect(120, 60, 69, 22))
self.comboBox.setObjectName(_fromUtf8("comboBox"))
self.comboBox.setEditable(True)
self.comboBox.addItems(self.comboData)
self.pushButton = QtGui.QPushButton(self.centralwidget)
self.pushButton.setGeometry(QtCore.QRect(260, 60, 75, 23))
self.pushButton.setObjectName(_fromUtf8("pushButton"))
self.pushButton.clicked.connect(self.load)
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtGui.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 456, 21))
self.menubar.setObjectName(_fromUtf8("menubar"))
MainWindow.setMenuBar(self.menubar)
self.statusbar = QtGui.QStatusBar(MainWindow)
self.statusbar.setObjectName(_fromUtf8("statusbar"))
MainWindow.setStatusBar(self.statusbar)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow", None))
self.pushButton.setText(_translate("MainWindow", "Load", None))
def load(self):
fileName=QFileDialog.getOpenFileName(MainWindow,'Load File')
data_pd=pd.read_csv(fileName,index_col=0,na_filter=False)
self.comboData=list(data_pd.var1)
print(self.comboData)
if __name__ == "__main__":
import sys
app = QtGui.QApplication(sys.argv)
MainWindow = QtGui.QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
MainWindow.show()
sys.exit(app.exec_())
you only load the data to self.comboData but do not load them to self.comboBox.
At the end of
def load(self):
add the following lines:
self.comboBox.clear() # delete all items from comboBox
self.comboBox.addItems(self.comboData) # add the actual content of self.comboData
As the model used by QComboBox emits the dataChanged() signal whenever the data in an item are changed, the combobox is repainted automatically and it is not necessary to update the combobox by
self.comboBox.update()
I'm trying to create a UI for an existing python program that I've made.
On the widget, I have two text boxes (QlineEdit) that I want to use to get the information for the program to use, a button and a textbrowser that will hold the output of the program.
I've stumbled upon PyQT4, which I installed using homebrew, and QT Creator. I've created the UI and converted it from a mainwindow.ui to a mainwindow.py and now I'm trying to figure out how to get the text input from the UI text boxes and have the program use it.
I cant figure out how to extract the text from the text boxes(QlineEdit) and store them in variables(strings) that the program can then use.
From my understanding, I should create a new .py file and import mainwindow as well as PyQT4.QtCore and PyQT4.QtGui. I dont know where to go from here so any insight would be helpful.
Also, how can I have the program print out to the textbrowser?
Maybe my approach is flawed and I should rebuild my program around the mainwindow.py file?
I apologize if this is all trivial information but I've never used PyQT or Qt creator.
Here is the code that I got from the the converted .ui to .py:
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'mainwindow.ui'
#
# Created: Wed Aug 13 15:25:22 2014
# by: PyQt4 UI code generator 4.11.1
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
def _fromUtf8(s):
return s
try:
_encoding = QtGui.QApplication.UnicodeUTF8
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig)
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName(_fromUtf8("MainWindow"))
MainWindow.resize(480, 385)
MainWindow.setWindowOpacity(1.0)
self.centralWidget = QtGui.QWidget(MainWindow)
self.centralWidget.setObjectName(_fromUtf8("centralWidget"))
self.textBrowser = QtGui.QTextBrowser(self.centralWidget)
self.textBrowser.setGeometry(QtCore.QRect(100, 120, 256, 192))
self.textBrowser.setObjectName(_fromUtf8("textBrowser"))
self.widget = QtGui.QWidget(self.centralWidget)
self.widget.setGeometry(QtCore.QRect(150, 10, 156, 97))
self.widget.setObjectName(_fromUtf8("widget"))
self.verticalLayout_2 = QtGui.QVBoxLayout(self.widget)
self.verticalLayout_2.setMargin(0)
self.verticalLayout_2.setObjectName(_fromUtf8("verticalLayout_2"))
self.verticalLayout = QtGui.QVBoxLayout()
self.verticalLayout.setObjectName(_fromUtf8("verticalLayout"))
self.lineEdit = QtGui.QLineEdit(self.widget)
self.lineEdit.setObjectName(_fromUtf8("lineEdit"))
self.verticalLayout.addWidget(self.lineEdit)
self.lineEdit_2 = QtGui.QLineEdit(self.widget)
self.lineEdit_2.setObjectName(_fromUtf8("lineEdit_2"))
self.verticalLayout.addWidget(self.lineEdit_2)
self.verticalLayout_2.addLayout(self.verticalLayout)
self.pushButton = QtGui.QPushButton(self.widget)
self.pushButton.setObjectName(_fromUtf8("pushButton"))
self.verticalLayout_2.addWidget(self.pushButton)
MainWindow.setCentralWidget(self.centralWidget)
self.menuBar = QtGui.QMenuBar(MainWindow)
self.menuBar.setGeometry(QtCore.QRect(0, 0, 480, 22))
self.menuBar.setObjectName(_fromUtf8("menuBar"))
MainWindow.setMenuBar(self.menuBar)
self.mainToolBar = QtGui.QToolBar(MainWindow)
self.mainToolBar.setObjectName(_fromUtf8("mainToolBar"))
MainWindow.addToolBar(QtCore.Qt.TopToolBarArea, self.mainToolBar)
self.statusBar = QtGui.QStatusBar(MainWindow)
self.statusBar.setObjectName(_fromUtf8("statusBar"))
MainWindow.setStatusBar(self.statusBar)
self.retranslateUi(MainWindow)
QtCore.QObject.connect(self.lineEdit, QtCore.SIGNAL(_fromUtf8("textEdited(QString)")), self.lineEdit.setText)
QtCore.QObject.connect(self.lineEdit_2, QtCore.SIGNAL(_fromUtf8("textEdited(QString)")), self.lineEdit_2.setText)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow", None))
self.lineEdit.setPlaceholderText(_translate("MainWindow", "Enter Case Number", None))
self.lineEdit_2.setPlaceholderText(_translate("MainWindow", "Number of cases", None))
self.pushButton.setText(_translate("MainWindow", "Submit", None))
if __name__ == "__main__":
import sys
app = QtGui.QApplication(sys.argv)
MainWindow = QtGui.QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
MainWindow.show()
sys.exit(app.exec_())
Any information helps. Thanks
The way UI works is that the UI forms the main loop of the program. Here mainwindow.py is your main loop. You can import your classes that you created in your program (lets call it code.py) or just paste that code into you mainwindow.py. Then on button press or some other kind of event, you can call a function that execute the main code of your code.py
To answer your other questions regarding how to use the text and print to the textbrowser try something like this:
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'mainwindow.ui'
#
# Created: Wed Aug 13 15:25:22 2014
# by: PyQt4 UI code generator 4.11.1
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
def _fromUtf8(s):
return s
try:
_encoding = QtGui.QApplication.UnicodeUTF8
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig)
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName(_fromUtf8("MainWindow"))
MainWindow.resize(480, 385)
MainWindow.setWindowOpacity(1.0)
self.centralWidget = QtGui.QWidget(MainWindow)
self.centralWidget.setObjectName(_fromUtf8("centralWidget"))
self.textBrowser = QtGui.QTextBrowser(self.centralWidget)
self.textBrowser.setGeometry(QtCore.QRect(100, 120, 256, 192))
self.textBrowser.setObjectName(_fromUtf8("textBrowser"))
self.widget = QtGui.QWidget(self.centralWidget)
self.widget.setGeometry(QtCore.QRect(150, 10, 156, 97))
self.widget.setObjectName(_fromUtf8("widget"))
self.verticalLayout_2 = QtGui.QVBoxLayout(self.widget)
self.verticalLayout_2.setMargin(0)
self.verticalLayout_2.setObjectName(_fromUtf8("verticalLayout_2"))
self.verticalLayout = QtGui.QVBoxLayout()
self.verticalLayout.setObjectName(_fromUtf8("verticalLayout"))
self.lineEdit = QtGui.QLineEdit(self.widget)
self.lineEdit.setObjectName(_fromUtf8("lineEdit"))
self.verticalLayout.addWidget(self.lineEdit)
self.lineEdit_2 = QtGui.QLineEdit(self.widget)
self.lineEdit_2.setObjectName(_fromUtf8("lineEdit_2"))
self.verticalLayout.addWidget(self.lineEdit_2)
self.verticalLayout_2.addLayout(self.verticalLayout)
self.pushButton = QtGui.QPushButton(self.widget)
self.pushButton.setObjectName(_fromUtf8("pushButton"))
self.verticalLayout_2.addWidget(self.pushButton)
MainWindow.setCentralWidget(self.centralWidget)
self.menuBar = QtGui.QMenuBar(MainWindow)
self.menuBar.setGeometry(QtCore.QRect(0, 0, 480, 22))
self.menuBar.setObjectName(_fromUtf8("menuBar"))
MainWindow.setMenuBar(self.menuBar)
self.mainToolBar = QtGui.QToolBar(MainWindow)
self.mainToolBar.setObjectName(_fromUtf8("mainToolBar"))
MainWindow.addToolBar(QtCore.Qt.TopToolBarArea, self.mainToolBar)
self.statusBar = QtGui.QStatusBar(MainWindow)
self.statusBar.setObjectName(_fromUtf8("statusBar"))
MainWindow.setStatusBar(self.statusBar)
self.retranslateUi(MainWindow)
QtCore.QObject.connect(self.lineEdit, QtCore.SIGNAL(_fromUtf8("textEdited(QString)")), self.lineEdit.setText)
QtCore.QObject.connect(self.lineEdit_2, QtCore.SIGNAL(_fromUtf8("textEdited(QString)")), self.lineEdit_2.setText)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow", None))
self.lineEdit.setPlaceholderText(_translate("MainWindow", "Enter Case Number", None))
self.lineEdit_2.setPlaceholderText(_translate("MainWindow", "Number of cases", None))
self.pushButton.setText(_translate("MainWindow", "Submit", None))
# Call a function when the button "Submit" is pressed
self.pushButton.clicked.connect(self.OnSubmit)
def OnSubmit(self):
# On submit do the necessary
# here I take the text from the LineEdits that you have
# (ie your Case Number, and number of Cases)
# and print them to the textbrowser below
text = self.lineEdit.text() + ' ' + self.lineEdit_2.text()
self.textBrowser.append(text)
if __name__ == "__main__":
import sys
app = QtGui.QApplication(sys.argv)
MainWindow = QtGui.QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
MainWindow.show()
sys.exit(app.exec_())
You can find some basic tutorials here: http://zetcode.com/gui/pyqt4/ that can help you understand the properties of your QtGui objects.