I want to add one functionality in my application when update is done then data in pyqt5 table should automatically refreshed with the new data in search results. But when I click the buttom, there is nothing happened.
# -*- coding: utf-8 -*-
from PyQt5 import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
import sys
import logging
import logging.config
import time
class Ui_Control_system(object):
def setupUi(self, Control_system):
Control_system.setObjectName("Control_system")
Control_system.resize(1004, 722)
Control_system.setFixedSize(1004, 722)
Control_system.setWindowIcon(QIcon('images/icon.png'))
Control_system.setStyleSheet("QMainWindow{border-image:url(images/background.jpg)}")
self.centralwidget = QtWidgets.QWidget(Control_system)
self.centralwidget.setObjectName("centralwidget")
#表格显示
self.tableWidget = QtWidgets.QTableWidget(self.centralwidget)
self.tableWidget.setGeometry(QtCore.QRect(130, 170, 752, 245))
self.tableWidget.setRowCount(8)
self.tableWidget.setColumnCount(6)
self.tableWidget.setObjectName("tableWidget")
self.tableWidget.horizontalHeader().setVisible(False)
self.tableWidget.horizontalHeader().setCascadingSectionResizes(False)
self.tableWidget.horizontalHeader().setDefaultSectionSize(125)
self.tableWidget.horizontalHeader().setHighlightSections(True)
self.tableWidget.horizontalHeader().setSortIndicatorShown(False)
self.tableWidget.verticalHeader().setVisible(False)
Control_system.setCentralWidget(self.centralwidget)
self.tableWidget.setAutoFillBackground(True)
self.tableWidget.setItem(0,0,QTableWidgetItem("机器编号"))
self.tableWidget.setItem(0,1,QTableWidgetItem("烟雾值"))
self.tableWidget.setItem(0,2,QTableWidgetItem("火焰值"))
self.tableWidget.setItem(0,3, QTableWidgetItem("温度值"))
self.tableWidget.setItem(0,4, QTableWidgetItem("电流值"))
self.tableWidget.setItem(0,5, QTableWidgetItem("电压值"))
font = QtGui.QFont()
font.setPointSize(15)
font.setBold(True)
self.tableWidget.item(0,0).setFont(font)
self.tableWidget.item(0,1).setFont(font)
self.tableWidget.item(0,2).setFont(font)
self.tableWidget.item(0,3).setFont(font)
self.tableWidget.item(0,4).setFont(font)
self.tableWidget.item(0,5).setFont(font)
self.label = QtWidgets.QLabel(self.centralwidget)
self.label.setGeometry(QtCore.QRect(360, 70, 300, 50))
self.label.setObjectName("label")
self.label.setAutoFillBackground(True)
self.label.setAlignment(Qt.AlignCenter)
self.label.setStyleSheet("border-image:url(images/title.png)")
self.pushButton = QtWidgets.QPushButton(self.centralwidget)
self.pushButton.setGeometry(QtCore.QRect(730, 480, 121, 41))
self.pushButton.setObjectName("pushButton")
self.pushButton.clicked.connect(self.slotStart)
Control_system.setCentralWidget(self.centralwidget)
self.statusbar = QtWidgets.QStatusBar(Control_system)
self.statusbar.setObjectName("statusbar")
Control_system.setStatusBar(self.statusbar)
self.retranslateUi(Control_system)
QtCore.QMetaObject.connectSlotsByName(Control_system)
def retranslateUi(self, Control_system):
_translate = QtCore.QCoreApplication.translate
Control_system.setWindowTitle(_translate("Control_system", "实时监控系统"))
self.pushButton.setText(_translate("Control_system", "开始运行"))
def slotStart(self):
#开始按钮不可点击,线程开始
self.pushButton.setEnabled(False)
self.update_data_thread = UpdateData()
self.update_data_thread.update_data.connect(self.set_btn)
self.update_data_thread.start()
def set_btn(self):
self.pushButton.setEnabled(True)
class UpdateData(QtCore.QThread):#使用qt自己本身的线程
update_data=QtCore.pyqtSignal()#因为这个信号槽要继承于Qobject,不然会发生没有emit,connect函数的报错,括号里面填写的是发射的数据类型
#print(".............")
def __init__(self):
super().__init__()
def run(self):
cnt = 0
while True:
cnt += 1
self.tableWidget.setItem(2,2,QTableWidgetItem(cnt))
self.update_data.emit() # 发射信号
time.sleep(1)
if __name__ == '__main__':
if not QtWidgets.QApplication.instance():
app = QtWidgets.QApplication(sys.argv)
else:
app = QtWidgets.QApplication.instance()
MainWindow = QtWidgets.QMainWindow()
ui = Ui_Control_system()
ui.setupUi(MainWindow) # 将ui实例绘制到窗口实例上
desktop = QtWidgets.QApplication.desktop()
x = (desktop.width() - MainWindow.width()) // 2
y = (desktop.height() - MainWindow.height()) // 2
MainWindow.move(x,y)
MainWindow.show()
sys.exit(app.exec())#exec_()方法的作用是“进入程序的主循环直到exit()被调
You cannot and should not modify the GUI directly from another thread, in your case QTableWidget and QTableWidgetItem are part of the GUI so the code: self.tableWidget.setItem(2, 2, QTableWidgetItem(cnt)) is incorrect. What should be done is to send the information to the main thread through elements that are thread-safe such as signals, QEvents, etc.
On the other hand PyQt recommends not modifying the class it generates but creating a widget and using the generated class as an interface(1).
Considering the above the solution is:
import sys
import time
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_Control_system(object):
def setupUi(self, Control_system):
Control_system.setObjectName("Control_system")
Control_system.resize(1004, 722)
Control_system.setFixedSize(1004, 722)
Control_system.setWindowIcon(QtGui.QIcon("images/icon.png"))
Control_system.setStyleSheet(
"QMainWindow{border-image:url(images/background.jpg)}"
)
self.centralwidget = QtWidgets.QWidget(Control_system)
self.centralwidget.setObjectName("centralwidget")
# 表格显示
self.tableWidget = QtWidgets.QTableWidget(self.centralwidget)
self.tableWidget.setGeometry(QtCore.QRect(130, 170, 752, 245))
self.tableWidget.setRowCount(8)
self.tableWidget.setColumnCount(6)
self.tableWidget.setObjectName("tableWidget")
self.tableWidget.horizontalHeader().setVisible(False)
self.tableWidget.horizontalHeader().setCascadingSectionResizes(False)
self.tableWidget.horizontalHeader().setDefaultSectionSize(125)
self.tableWidget.horizontalHeader().setHighlightSections(True)
self.tableWidget.horizontalHeader().setSortIndicatorShown(False)
self.tableWidget.verticalHeader().setVisible(False)
Control_system.setCentralWidget(self.centralwidget)
self.tableWidget.setAutoFillBackground(True)
self.tableWidget.setItem(0, 0, QtWidgets.QTableWidgetItem("机器编号"))
self.tableWidget.setItem(0, 1, QtWidgets.QTableWidgetItem("烟雾值"))
self.tableWidget.setItem(0, 2, QtWidgets.QTableWidgetItem("火焰值"))
self.tableWidget.setItem(0, 3, QtWidgets.QTableWidgetItem("温度值"))
self.tableWidget.setItem(0, 4, QtWidgets.QTableWidgetItem("电流值"))
self.tableWidget.setItem(0, 5, QtWidgets.QTableWidgetItem("电压值"))
font = QtGui.QFont()
font.setPointSize(15)
font.setBold(True)
self.tableWidget.item(0, 0).setFont(font)
self.tableWidget.item(0, 1).setFont(font)
self.tableWidget.item(0, 2).setFont(font)
self.tableWidget.item(0, 3).setFont(font)
self.tableWidget.item(0, 4).setFont(font)
self.tableWidget.item(0, 5).setFont(font)
self.label = QtWidgets.QLabel(self.centralwidget)
self.label.setGeometry(QtCore.QRect(360, 70, 300, 50))
self.label.setObjectName("label")
self.label.setAutoFillBackground(True)
self.label.setAlignment(QtCore.Qt.AlignCenter)
self.label.setStyleSheet("border-image:url(images/title.png)")
self.pushButton = QtWidgets.QPushButton(self.centralwidget)
self.pushButton.setGeometry(QtCore.QRect(730, 480, 121, 41))
self.pushButton.setObjectName("pushButton")
Control_system.setCentralWidget(self.centralwidget)
self.statusbar = QtWidgets.QStatusBar(Control_system)
self.statusbar.setObjectName("statusbar")
Control_system.setStatusBar(self.statusbar)
self.retranslateUi(Control_system)
QtCore.QMetaObject.connectSlotsByName(Control_system)
def retranslateUi(self, Control_system):
_translate = QtCore.QCoreApplication.translate
Control_system.setWindowTitle(_translate("Control_system", "实时监控系统"))
self.pushButton.setText(_translate("Control_system", "开始运行"))
class Control_system(QtWidgets.QMainWindow, Ui_Control_system):
def __init__(self, parent=None):
super().__init__(parent)
self.setupUi(self)
self.pushButton.clicked.connect(self.slotStart)
#QtCore.pyqtSlot()
def slotStart(self):
self.pushButton.setEnabled(False)
self.update_data_thread = UpdateData(self)
self.update_data_thread.dataChanged.connect(self.onDataChanged)
self.update_data_thread.start()
#QtCore.pyqtSlot(int, int, str)
def onDataChanged(self, row, column, text):
it = self.tableWidget.item(row, column)
if it is None:
it = QtWidgets.QTableWidgetItem()
self.tableWidget.setItem(row, column, it)
it.setText(text)
class UpdateData(QtCore.QThread):
dataChanged = QtCore.pyqtSignal(int, int, str)
def run(self):
cnt = 0
while True:
cnt += 1
self.dataChanged.emit(2, 2, str(cnt))
time.sleep(1)
if __name__ == "__main__":
app = QtWidgets.QApplication.instance()
if app is None:
app = QtWidgets.QApplication(sys.argv)
w = Control_system()
w.show()
sys.exit(app.exec_())
Update:
class Control_system(QtWidgets.QMainWindow, Ui_Control_system):
def __init__(self, parent=None):
super().__init__(parent)
self.setupUi(self)
self.pushButton.clicked.connect(self.slotStart)
self.pushButton_2.clicked.connect(self.slotStop)
#QtCore.pyqtSlot()
def slotStart(self):
# ...
#QtCore.pyqtSlot(int, int, str)
def onDataChanged(self, row, column, text):
it = self.tableWidget.item(row, column)
if it is None:
it = QtWidgets.QTableWidgetItem()
self.tableWidget.setItem(row, column, it)
it.setText(text)
#QtCore.pyqtSlot()
def slotStop(self):
self.update_data_thread.requestInterruption()
self.update_data_thread.quit()
self.update_data_thread.wait()
self.pushButton.setEnabled(True)
class UpdateData(QtCore.QThread):
dataChanged = QtCore.pyqtSignal(int, int, str)
def run(self):
cnt = 0
while not self.isInterruptionRequested(): # <---
cnt += 1
self.dataChanged.emit(2, 2, str(cnt))
time.sleep(1)
(1) Using the Generated Code
Related
I am using QListWidget, QSqlTableModel, QtableView and QDataWidgetMapper. QListWidget is ItemIsUserCheckable.
I am able to save selected items from QListWidget into QtSql table in a single field as string format(converting list items into string as "Green, Green Grapes, Oranges".
But at the same time i want to change the selected item and update the items from QListWidget of the String data. How to do. Is it possible. Or PLease let me know if any other solution.
Below is the Example code:
from PyQt5 import QtCore, QtGui, QtWidgets, QtSql
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtSql import *
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(391, 496)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.listWidget = QtWidgets.QListWidget(self.centralwidget)
self.listWidget.setGeometry(QtCore.QRect(9, 9, 373, 188))
self.listWidget.setObjectName("listWidget")
self.save_btn = QtWidgets.QPushButton(self.centralwidget)
self.save_btn.setGeometry(QtCore.QRect(100, 230, 75, 23))
self.save_btn.setObjectName("save_btn")
self.label = QtWidgets.QLabel(self.centralwidget)
self.label.setGeometry(QtCore.QRect(9, 203, 27, 16))
self.label.setObjectName("label")
self.lineEdit = QtWidgets.QLineEdit(self.centralwidget)
self.lineEdit.setGeometry(QtCore.QRect(56, 203, 181, 20))
self.lineEdit.setObjectName("lineEdit")
self.update_btn = QtWidgets.QPushButton(self.centralwidget)
self.update_btn.setGeometry(QtCore.QRect(293, 229, 75, 23))
self.update_btn.setObjectName("update_btn")
self.edit_btn = QtWidgets.QPushButton(self.centralwidget)
self.edit_btn.setGeometry(QtCore.QRect(199, 229, 75, 23))
self.edit_btn.setObjectName("edit_btn")
self.tableView = QtWidgets.QTableView(self.centralwidget)
self.tableView.setGeometry(QtCore.QRect(9, 258, 373, 188))
self.tableView.setObjectName("tableView")
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 391, 21))
self.menubar.setObjectName("menubar")
MainWindow.setMenuBar(self.menubar)
self.statusbar = QtWidgets.QStatusBar(MainWindow)
self.statusbar.setObjectName("statusbar")
MainWindow.setStatusBar(self.statusbar)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
db = QtSql.QSqlDatabase.addDatabase("QSQLITE")
db.setDatabaseName("fruites.db")
if db.open():
if db.open():
query = QSqlQuery()
query.exec_("""CREATE TABLE IF NOT EXISTS store(name TEXT, items TEXT)""")
self.store_model = QtSql.QSqlTableModel()
self.store_model.setTable("store")
self.store_model.select()
self.tableView.setModel(self.store_model)
list_ = ["Green", "Green Apple","Green Grapes", "Bananas", "Oranges"]
list_ = dict.fromkeys(list_, 0)
for i in list_:
item = QtWidgets.QListWidgetItem(i)
item.setFlags(item.flags() | QtCore.Qt.ItemIsUserCheckable)
item.setCheckState(QtCore.Qt.Unchecked)
self.listWidget.addItem(item)
self.save_btn.clicked.connect(self.save_item)
self.edit_btn.clicked.connect(self.edit_item)
self.update_btn.clicked.connect(self.submit_item)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
self.save_btn.setText(_translate("MainWindow", "Save"))
self.label.setText(_translate("MainWindow", "Name"))
self.update_btn.setText(_translate("MainWindow", "Update"))
self.edit_btn.setText(_translate("MainWindow", "Edit"))
def save_item(self):
name = self.lineEdit.text()
strng = ''
checked = []
for row in range(self.listWidget.count()):
item = self.listWidget.item(row)
if item.checkState():
checked.append(item)
strng = ", " .join(i.text() for i in checked)
r = self.store_model.record()
r.setValue("name", name)
r.setValue("items", strng)
self.store_model.insertRecord(-1, r)
self.store_model.select()
self.lineEdit.clear()
for i in range(self.listWidget.count()):
item = self.listWidget.item(i)
item.setCheckState(QtCore.Qt.Unchecked)
def edit_item(self):
selected = self.tableView.selectedIndexes()
if not self.store_model.rowCount():
return
index = self.tableView.currentIndex()
if index.isValid():
row = index.row()
else:
row = 0
self.store_mapper = QtWidgets.QDataWidgetMapper()
self.store_mapper.setSubmitPolicy(QtWidgets.QDataWidgetMapper.ManualSubmit)
self.store_mapper.setModel(self.tableView.model())
self.store_mapper.addMapping(self.lineEdit, 0)
self.store_mapper.addMapping(self.listWidget, 1)
self.store_mapper.setCurrentIndex(row)
def submit_item(self):
self.store_mapper.submit()
self.lineEdit.clear()
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_())
I have a QGraphicsView with a QGraphicsScene. On QGraphicsScene, I output the image using QGraphicsPixmapItem. And I would like to draw an ellipse over the image with my mouse.
I have that code now. And the ellipse is drawn on MainWindow.
What do I need to do to have the ellipse drawn on an image in QGraphicsView?
Code OFT_MainWindow
# OFT_MainWindow
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(862, 710)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.graphicsView = QtWidgets.QGraphicsView(self.centralwidget)
self.graphicsView.setGeometry(QtCore.QRect(10, 90, 841, 571))
self.graphicsView.setMouseTracking(True)
self.graphicsView.setObjectName("graphicsView")
self.buttonBox = QtWidgets.QDialogButtonBox(self.centralwidget)
self.buttonBox.setGeometry(QtCore.QRect(360, 670, 81, 31))
font = QtGui.QFont()
font.setPointSize(10)
self.buttonBox.setFont(font)
self.buttonBox.setOrientation(QtCore.Qt.Horizontal)
self.buttonBox.setStandardButtons(QtWidgets.QDialogButtonBox.Ok)
self.buttonBox.setObjectName("buttonBox")
self.pushButton = QtWidgets.QPushButton(self.centralwidget)
self.pushButton.setGeometry(QtCore.QRect(760, 10, 91, 31))
font = QtGui.QFont()
font.setPointSize(10)
self.pushButton.setFont(font)
self.pushButton.setObjectName("pushButton")
self.lineEdit = QtWidgets.QLineEdit(self.centralwidget)
self.lineEdit.setGeometry(QtCore.QRect(10, 10, 731, 31))
self.lineEdit.setObjectName("lineEdit")
self.lineEdit_2 = QtWidgets.QLineEdit(self.centralwidget)
self.lineEdit_2.setGeometry(QtCore.QRect(10, 670, 331, 31))
self.lineEdit_2.setObjectName("lineEdit_2")
self.pushButton_2 = QtWidgets.QPushButton(self.centralwidget)
self.pushButton_2.setGeometry(QtCore.QRect(10, 50, 841, 31))
font = QtGui.QFont()
font.setPointSize(10)
self.pushButton_2.setFont(font)
self.pushButton_2.setObjectName("pushButton_2")
MainWindow.setCentralWidget(self.centralwidget)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
self.pushButton.setText(_translate("MainWindow", "Browse"))
self.pushButton_2.setText(_translate("MainWindow", "Highlight field area"))
Main code
import OFT_MainWindow
import sys
import os
import numpy as np
import cv2
from PIL import Image, ImageQt, ImageEnhance
from PyQt5 import QtWidgets
from PyQt5 import QtGui
from PyQt5 import QtCore
from PyQt5.QtCore import Qt, QPoint
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.Qt import Qt
def main():
app = QtWidgets.QApplication(sys.argv)
window = MainWindow()
window.show()
app.exec_()
class MainWindow(QtWidgets.QMainWindow, OFT_MainWindow.Ui_MainWindow, QtWidgets.QGraphicsView, QtWidgets.QGraphicsScene):
def __init__(self, parent=None):
super().__init__(parent)
self.setupUi(self)
self.pushButton.clicked.connect(self.browse_file)
self.pushButton_2.clicked.connect(self.imageFrame)
self.begin = QtCore.QPoint()
self.end = QtCore.QPoint()
self.show()
###################################################################################
def browse_file(self):
self.lineEdit.clear()
file = QtWidgets.QFileDialog.getOpenFileName(self, "Choose file")
file = str(file[0])
if file:
self.lineEdit.setText(file) # добавить путь в lineEdit
# cap = cv2.VideoCapture(file)
###################################################################################
def imageFrame(self):
file = self.lineEdit.text()
self.drawing = False
self.lastPoint = QPoint()
scene = QtWidgets.QGraphicsScene(self)
self.image = QPixmap(file)
item = QtWidgets.QGraphicsPixmapItem(self.image)
scene.addItem(item)
view = self.graphicsView.setScene(scene)
# self.show()
def paintEvent(self, event):
qp = QtGui.QPainter(self)
br = QtGui.QBrush(QtGui.QColor(0, 255, 0, 25))
qp.setBrush(br)
ellipse = qp.drawEllipse(QtCore.QRect(self.begin, self.end))
coord_a = self.begin
coord_a = str(coord_a)
coord_a = coord_a[20:][:-1]
coord_b = self.end
coord_b = str(coord_b)
coord_b = coord_b[20:][:-1]
coord = ('begin = ' + coord_a + ' end = ' + coord_b)
self.lineEdit_2.setText(coord)
def mousePressEvent(self, event):
self.begin = event.pos()
self.end = event.pos()
self.update()
def mouseMoveEvent(self, event):
self.end = event.pos()
self.update()
###################################################################################
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
window = MainWindow()
window.show()
app.aboutToQuit.connect(app.deleteLater)
sys.exit(app.exec_())
If you want to paint something on a QGraphicsView, you have to add QGraphicsItem to its scene, otherwise you're making almost useless to crete a QGraphicsView to begin with.
One possible solution is to install an event filter on the scene, listen for mouse button events and draw an ellipse (using QGraphicsEllipseItem) on the scene if the first click is done within the contents of a QGraphicsPixmapItem.
Note that another possibility is to subclass from QGraphicsPixmapItem and implement its mouse events instead. It all depends on what you're going to do and what you're going to need from your program.
class MainWindow(QtWidgets.QMainWindow, OFT_MainWindow.Ui_MainWindow):
def __init__(self, parent=None):
super().__init__(parent)
# ...
self.ellipseItem = None
def imageFrame(self):
# ...
scene.installEventFilter(self)
def eventFilter(self, source, event):
if event.type() == QtCore.QEvent.GraphicsSceneMousePress:
for item in self.graphicsView.scene().items(event.scenePos()):
if isinstance(item, QtWidgets.QGraphicsPixmapItem):
self.reference = item
self.ellipseItem = QtWidgets.QGraphicsEllipseItem(item)
self.ellipseItem.setBrush(QtGui.QColor(0, 255, 0, 25))
self.start = item.mapFromScene(event.scenePos())
elif event.type() == QtCore.QEvent.GraphicsSceneMouseMove and self.ellipseItem:
end = self.reference.mapFromScene(event.scenePos())
self.ellipseItem.setRect(QtCore.QRectF(self.start, end))
elif event.type() == QtCore.QEvent.GraphicsSceneMouseRelease and self.ellipseItem:
self.ellipseItem = None
return super().eventFilter(source, event)
Note that subclassing your Main window from all those classes (QtWidgets.QMainWindow, OFT_MainWindow.Ui_MainWindow, QtWidgets.QGraphicsView, QtWidgets.QGraphicsScene) is not only unnecessary and meaningless, but absolutely WRONG: multiple-inheritance subclassing should only be done when you know what you're inheriting from and why, otherwise, just don't. For Qt widgets that load from UI files, just subclass from the base widget class and the Ui.
I have a PyQt5 QTableWidget for which I want to detect double-right-click events.
Here is my 'design.py' module:
from PyQt5 import QtCore, QtWidgets
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(790, 472)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.tbwMain = QtWidgets.QTabWidget(self.centralwidget)
self.tbwMain.setGeometry(QtCore.QRect(0, 0, 801, 451))
self.tbwMain.setObjectName("tbwMain")
self.tabBoxes = QtWidgets.QWidget()
self.tabBoxes.setObjectName("tabBoxes")
self.horizontalLayoutWidget = QtWidgets.QWidget(self.tabBoxes)
self.horizontalLayoutWidget.setGeometry(QtCore.QRect(0, 0, 791, 421))
self.horizontalLayoutWidget.setObjectName("horizontalLayoutWidget")
self.horizontalLayout = QtWidgets.QHBoxLayout(self.horizontalLayoutWidget)
self.horizontalLayout.setContentsMargins(0, 0, 0, 0)
self.horizontalLayout.setObjectName("horizontalLayout")
spacerItem = QtWidgets.QSpacerItem(220, 40, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding)
self.horizontalLayout.addItem(spacerItem)
self.tblBoxes = QtWidgets.QTableWidget(self.horizontalLayoutWidget)
self.tblBoxes.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOn)
self.tblBoxes.setVerticalScrollMode(QtWidgets.QAbstractItemView.ScrollPerPixel)
self.tblBoxes.setRowCount(1)
self.tblBoxes.setObjectName("tblBoxes")
self.tblBoxes.setColumnCount(3)
item = QtWidgets.QTableWidgetItem()
self.tblBoxes.setHorizontalHeaderItem(0, item)
item = QtWidgets.QTableWidgetItem()
self.tblBoxes.setHorizontalHeaderItem(1, item)
item = QtWidgets.QTableWidgetItem()
self.tblBoxes.setHorizontalHeaderItem(2, item)
item = QtWidgets.QTableWidgetItem()
item.setTextAlignment(QtCore.Qt.AlignCenter)
self.tblBoxes.setItem(0, 0, item)
item = QtWidgets.QTableWidgetItem()
item.setTextAlignment(QtCore.Qt.AlignCenter)
self.tblBoxes.setItem(0, 1, item)
item = QtWidgets.QTableWidgetItem()
item.setTextAlignment(QtCore.Qt.AlignCenter)
self.tblBoxes.setItem(0, 2, item)
self.tblBoxes.horizontalHeader().setStretchLastSection(True)
self.tblBoxes.verticalHeader().setVisible(False)
self.horizontalLayout.addWidget(self.tblBoxes)
spacerItem1 = QtWidgets.QSpacerItem(220, 40, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding)
self.horizontalLayout.addItem(spacerItem1)
self.tbwMain.addTab(self.tabBoxes, "")
MainWindow.setCentralWidget(self.centralwidget)
self.statusbar = QtWidgets.QStatusBar(MainWindow)
self.statusbar.setObjectName("statusbar")
MainWindow.setStatusBar(self.statusbar)
self.retranslateUi(MainWindow)
self.tbwMain.setCurrentIndex(0)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
# - - - - -
self.tblBoxes.doubleClicked.connect(self.tblMouseDoubleClick)
def tblMouseDoubleClick(self):
pass #Get event somehow?
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_())
As well as my 'main.py' module:
from PyQt5 import QtCore, QtGui, QtWidgets
from design import Ui_MainWindow
import shared.components.tables as tbl
from unshared import boxes as bxs
import switch as swb
stop_threads = False
class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow):
def __init__(self, *args, **kwargs):
QtWidgets.QMainWindow.__init__(self, *args, **kwargs)
self.setupUi(self)
load(self)
def mouseDoubleClickEvent(self, QMouseEvent):
if event.type() == QtCore.QEvent.MouseButtonPress:
if event.button() == QtCore.Qt.RightButton:
print('Double right-click!')
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
w = MainWindow()
w.show()
sys.exit(app.exec_())
I've tried setting up the event by using mouseDoubleClickEvent in the main.py module; however, the clicks only register when clicking in areas of the main window outside of the table.
I've also considered using connect (as shown in design.py), but I don't know how to check to see if the right mouse button is being clicked without the mouse event - and I'm not sure if it is possible for me to get the mouse event. I just want to make it so that when the user double-right-clicks on a cell in my table (tblBoxes) I can detect the event.
Is this possible with either of the methods I've proposed? I'm using Qt Designer, so the less invasive the solution the better.
You can use an event-filter to watch for a MouseButtonDblClick event:
class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow):
def __init__(self, *args, **kwargs):
...
self.tblBoxes.viewport().installEventFilter(self)
def eventFilter(self, source, event):
if (event.type() == QtCore.QEvent.MouseButtonDblClick and
event.buttons() == QtCore.Qt.RightButton and
source is self.tblBoxes.viewport()):
item = self.tblBoxes.itemAt(event.pos())
if item is not None:
print('dblclick:', item.row(), item.column())
return super(MainWindow, self).eventFilter(source, event)
just like the title says i'm trying to draw inside an existing QGraphicsView. The window I generated using QT Designer, and I would like to draw a matrix of 16x16 squares inside the QGraphicsView.
This is the code I have as of right now:
Window:
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'untitled.ui'
#
# Created by: PyQt5 UI code generator 5.8.2
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(911, 567)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.label = QtWidgets.QLabel(self.centralwidget)
self.label.setGeometry(QtCore.QRect(20, 10, 301, 31))
font = QtGui.QFont()
font.setPointSize(12)
font.setBold(True)
font.setWeight(75)
self.label.setFont(font)
self.label.setObjectName("label")
self.groupBox = QtWidgets.QGroupBox(self.centralwidget)
self.groupBox.setGeometry(QtCore.QRect(620, 40, 271, 91))
font = QtGui.QFont()
font.setBold(True)
font.setWeight(75)
self.groupBox.setFont(font)
self.groupBox.setObjectName("groupBox")
self.rdtest = QtWidgets.QRadioButton(self.groupBox)
self.rdtest.setGeometry(QtCore.QRect(60, 60, 101, 22))
self.rdtest.setObjectName("rdtest")
self.rdtrain = QtWidgets.QRadioButton(self.groupBox)
self.rdtrain.setGeometry(QtCore.QRect(60, 30, 101, 22))
self.rdtrain.setObjectName("rdtrain")
self.graphicsView = QtWidgets.QGraphicsView(self.centralwidget)
self.graphicsView.setGeometry(QtCore.QRect(10, 40, 601, 411))
self.graphicsView.setObjectName("graphicsView")
self.clear = QtWidgets.QPushButton(self.centralwidget)
self.clear.setGeometry(QtCore.QRect(10, 470, 88, 29))
self.clear.setObjectName("clear")
self.trainNewInput = QtWidgets.QPushButton(self.centralwidget)
self.trainNewInput.setGeometry(QtCore.QRect(500, 470, 111, 29))
self.trainNewInput.setObjectName("trainNewInput")
self.trainbox = QtWidgets.QGroupBox(self.centralwidget)
self.trainbox.setGeometry(QtCore.QRect(620, 150, 271, 171))
font = QtGui.QFont()
font.setBold(True)
font.setWeight(75)
self.trainbox.setFont(font)
self.trainbox.setObjectName("trainbox")
self.vtrain = QtWidgets.QLineEdit(self.trainbox)
self.vtrain.setGeometry(QtCore.QRect(100, 70, 101, 29))
self.vtrain.setObjectName("vtrain")
self.label_2 = QtWidgets.QLabel(self.trainbox)
self.label_2.setGeometry(QtCore.QRect(40, 70, 56, 31))
font = QtGui.QFont()
font.setBold(True)
font.setWeight(75)
self.label_2.setFont(font)
self.label_2.setObjectName("label_2")
self.trainDefault = QtWidgets.QPushButton(self.trainbox)
self.trainDefault.setGeometry(QtCore.QRect(40, 30, 161, 29))
self.trainDefault.setObjectName("trainDefault")
self.output = QtWidgets.QLabel(self.trainbox)
self.output.setGeometry(QtCore.QRect(10, 130, 271, 17))
self.output.setText("")
self.output.setObjectName("output")
self.output_2 = QtWidgets.QLabel(self.trainbox)
self.output_2.setGeometry(QtCore.QRect(10, 150, 271, 17))
self.output_2.setText("")
self.output_2.setObjectName("output_2")
self.testbox = QtWidgets.QGroupBox(self.centralwidget)
self.testbox.setGeometry(QtCore.QRect(620, 330, 271, 171))
font = QtGui.QFont()
font.setBold(True)
font.setWeight(75)
self.testbox.setFont(font)
self.testbox.setObjectName("testbox")
self.pushButton = QtWidgets.QPushButton(self.testbox)
self.pushButton.setGeometry(QtCore.QRect(50, 40, 161, 29))
self.pushButton.setObjectName("pushButton")
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 911, 23))
self.menubar.setObjectName("menubar")
MainWindow.setMenuBar(self.menubar)
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"))
self.label.setText(_translate("MainWindow", "RNA: Numeros "))
self.groupBox.setTitle(_translate("MainWindow", "Opciones:"))
self.rdtest.setText(_translate("MainWindow", "Test"))
self.rdtrain.setText(_translate("MainWindow", "Train"))
self.clear.setText(_translate("MainWindow", "Clear"))
self.trainNewInput.setText(_translate("MainWindow", "Train new Input"))
self.trainbox.setTitle(_translate("MainWindow", "Train:"))
self.label_2.setText(_translate("MainWindow", "% Test:"))
self.trainDefault.setText(_translate("MainWindow", "Train Default Data"))
self.testbox.setTitle(_translate("MainWindow", "Test:"))
self.pushButton.setText(_translate("MainWindow", "Start Test"))
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_())
Logic class where I want to create a method that draws on the QGraphicsView from the window:
import sys
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import QGraphicsScene
from PyQt5.QtCore import (QLineF, QPointF, QRectF, Qt)
from PyQt5.QtWidgets import QWidget, QApplication
from PyQt5.QtWidgets import (QApplication, QGraphicsView, QGraphicsScene, QGraphicsItem,
QGridLayout, QVBoxLayout, QHBoxLayout,
QLabel, QLineEdit, QPushButton)
from window import Ui_MainWindow
from RNA import NumberIA
train = []
train_r = []
test = []
test_r = []
class MyFirstGuiProgram(Ui_MainWindow):
def __init__(self, dialog):
Ui_MainWindow.__init__(self)
self.setupUi(dialog)
self.rdtrain.setChecked(True)
# Connect "add" button with a custom function (addInputTextToListbox)
self.clear.clicked.connect(self.addInputTextToListbox)
self.trainDefault.clicked.connect(self.t_DefaultData)
self.rdtest.clicked.connect(self.enableTest)
self.rdtrain.clicked.connect(self.enableTrain)
def enableTest(self):
self.trainbox.setEnabled(False)
self.trainNewInput.setEnabled(False)
self.testbox.setEnabled(True)
def drawSomething(self):
tes = "f"
def enableTrain(self):
self.trainbox.setEnabled(True)
self.trainNewInput.setEnabled(True)
self.testbox.setEnabled(False)
def addInputTextToListbox(self):
print("Hello world!!!")
def t_DefaultData(self):
ann = NumberIA()
t = self.vtrain.text()
print("Training data: ", t)
global train
global train_r
global test
global test_r
train, train_r, test, test_r = ann.read_file(float(t))
self.output.setText("Train complete...")
ann.crear_red(train, train_r)
accuracy, matrix = ann.probar_red(test, test_r)
self.output_2.setText("Accuracy: " + str(accuracy * 100) + "%")
print("Matris de Confusion:")
print('\n'.join([''.join(['{:4}'.format(item) for item in row])
for row in matrix]))
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
MainWindow = QtWidgets.QMainWindow()
ui = MyFirstGuiProgram(MainWindow)
MainWindow.show()
MainWindow.setWindowTitle("RNA: Inteligencia Artificial 2")
ui.enableTrain()
sys.exit(app.exec_())
I cant seem to find examples on how to to this online, the examples I have found are vague to me and cant seem to figure it out.
I recommend you inherit from QMainWindow and implement the Ui_MainWindow interface, to draw in a QGraphicsView you must use a QGraphicsScene, and use its methods, in this case use addRect().
from PyQt5 import QtCore, QtGui, QtWidgets
class MyFirstGuiProgram(QtWidgets.QMainWindow, Ui_MainWindow):
def __init__(self, parent=None):
QtWidgets.QMainWindow.__init__(self, parent=parent)
self.setupUi(self)
scene = QtWidgets.QGraphicsScene()
self.graphicsView.setScene(scene)
pen = QtGui.QPen(QtCore.Qt.green)
side = 20
for i in range(16):
for j in range(16):
r = QtCore.QRectF(QtCore.QPointF(i*side, j*side), QtCore.QSizeF(side, side))
scene.addRect(r, pen)
if __name__ == '__main__':
import sys
app = QtWidgets.QApplication(sys.argv)
w = MyFirstGuiProgram()
w.show()
sys.exit(app.exec_())
You can also draw it by QLineF(), it gives more control from design point of view.
import sys
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
def sceneWithPen(grid):
scene = QGraphicsScene()
view = QGraphicsView()
view.setScene(scene)
# Creating line's colors
red = QColor(qRgb(172, 50, 99))
blue = QColor(qRgb(50, 150, 203))
# Set length of square's side and number of horizontal and vertical lines
vLines = 16
hLines = 16
side = 30
# Set starting values for loops
hor = 0
ver = 0
subdiv = 16
leftX,leftY = 0, 0
rightX, rightY = subdiv*side, 0
bottomX, bottomY= 0, 0
topX, topY = 0, subdiv*side
while ver < vLines:
# Drawing vertical lines
ver = ver + 1
vLine = QLineF(bottomX, bottomY, topX, topY)
bottomX, topX = bottomX + side, topX + side
scene.addLine(vLine, red)
while hor < hLines:
#Drawing horizontal lines
hor = hor + 1
hLine = QLineF(leftX, leftY, rightX, rightY)
leftY, rightY = leftY + side, rightY + side
scene.addLine(hLine, blue)
grid.addWidget(view)
if __name__ == '__main__':
app = QApplication(sys.argv)
w = QWidget()
grid = QGridLayout()
sceneWithPen(grid)
w.setLayout(grid)
w.show()
sys.exit(app.exec_())
It will be like this:
Great example #eyllanesc just gave you right above, here is another small example I just happened to have laying around, if you need to draw like a simple free hand.
Have your MainWindow, for example a QMainWindow or Qwidget or...
Have a QGraphicsView.
Set the QGraphicsView's scene with your QGraphicsScene
Have your own QGraphicsPathItem so you can set properties you need.
Have the implementation of what you want to draw inside your scene, so it knows how to draw on itself.
Having things in this way you will have control of several scenes knowing how to draw on itself independently, of course if you will need more than one scene.
This example the logic were implemented inside the QGraphicsView, you could move it to your GraphicsScene.
class MainWindow(QMainWindow):
central_widget = None
layout_container = None
def __init__(self):
super(MainWindow, self).__init__()
self.central_widget = QWidget()
self.layout_container = QVBoxLayout()
self.central_widget.setLayout(self.layout_container)
self.setCentralWidget(self.central_widget)
self.layout_container.addWidget(GraphicsView())
class GraphicsView(QGraphicsView):
start = None
end = None
item = None
path = None
def __init__(self):
super(GraphicsView, self).__init__()
self.setScene(QGraphicsScene())
self.path = QPainterPath()
self.item = GraphicsPathItem()
self.scene().addItem(self.item)
def mousePressEvent(self, event):
self.start = self.mapToScene(event.pos())
self.path.moveTo(self.start)
def mouseMoveEvent(self, event):
self.end = self.mapToScene(event.pos())
self.path.lineTo(self.end)
self.start = self.end
self.item.setPath(self.path)
class GraphicsPathItem(QGraphicsPathItem):
def __init__(self):
super(GraphicsPathItem, self).__init__()
pen = QPen()
pen.setColor(Qt.black)
pen.setWidth(10)
self.setPen(pen)
if __name__ == '__main__':
app = QApplication(sys.argv)
mw = MainWindow()
mw.show()
sys.exit(app.exec_())
I am working with code http://pastebin.com/3JZWP14y to fix my errors in code below. I need to know the proper way to launch another widget/dialog for text entry to my list.
Below was my original code.
I have my app that displays a table, the child widget to add a row opens and closes fine but then my parent crashes. Code to parent is below. The child closes with sys.exit(app.exec_()) The child also opens the todo.p file but closes all pointers to file.
from PyQt4.QtGui import (QMainWindow, QApplication)
from PyQt4 import QtCore, QtGui
from PyQt4.QtCore import *
from PyQt4.QtGui import *
import pickle as p
import sys
import addit
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.d=self.getdata()
self.d={"12345678":["do some stuff here that needs to be in a large cell to wrap text","1",1],"12343378":["do stuff","1",1]}
self.setmydata(self.d)
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.QTableWidget(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)
self.pushButton.clicked.connect(lambda: self.openaddit())
def openaddit(self):
x=addit.openwindow()
print "clean"
#reload?
def createfile(self,d):
f=open('todo.d',"w")
p.dump(d,f)
f.close
def getdata(self):
if os.path.isfile('todo.p'):
print "here"
d= p.load(open('todo.p', 'r'))
else:
print "here2"
d={}
self.createfile(d)
print d,"hereeeee"
return d
def setmydata(self,d):
self.data = {}
keys=d.keys()
self.data['col1']=keys
self.data['col2']=[]
self.tableView.setRowCount(len(keys))
self.tableView.setColumnCount(2)
self.tableView.setHorizontalHeaderLabels(['SR', 'Notes'])
for i in range(0,len(keys)):
if d[keys[i]][2]==0:
continue
self.tableView.setItem(i, 0, QtGui.QTableWidgetItem(keys[i]))
self.tableView.setItem(i, 1, QtGui.QTableWidgetItem(d[keys[i]][0]))
self.pushButton = QtGui.QPushButton(self.centralwidget)
self.tableView.setRowHeight(i,100)
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_()
addit.openwindow() calls the below program.
import sys
from PyQt4 import QtCore, QtGui
#import numpy as np
import pickle as p
class MyQDialog(QtGui.QDialog):
def __init__(self, parent=None):
super(MyQDialog, self).__init__(parent)
## Default values
self.d={}
## Create labels and buttons
#self.setObjectName(("Dialog"))
self.resize(400, 279)
self.d ={}
self.buttonBox = QtGui.QDialogButtonBox(self)
self.buttonBox.setGeometry(QtCore.QRect(30, 240, 341, 32))
self.buttonBox.setOrientation(QtCore.Qt.Horizontal)
self.buttonBox.setStandardButtons(QtGui.QDialogButtonBox.Cancel|QtGui.QDialogButtonBox.Ok)
self.buttonBox.setObjectName(("buttonBox"))
self.lineEdit = QtGui.QLineEdit(self)
self.lineEdit.setGeometry(QtCore.QRect(40, 20, 141, 31))
self.lineEdit.setObjectName(("lineEdit"))
self.textEdit = QtGui.QTextEdit(self)
self.textEdit.setGeometry(QtCore.QRect(20, 60, 361, 161))
self.textEdit.setObjectName(("textEdit"))
self.textEdit.setTabChangesFocus(True)
self.spinBox = QtGui.QSpinBox(self)
self.spinBox.setGeometry(QtCore.QRect(260, 21, 61, 31))
self.spinBox.setMinimum(1)
self.spinBox.setObjectName(("spinBox"))
self.label = QtGui.QLabel(self)
self.label.setGeometry(QtCore.QRect(10, 26, 21, 21))
font = QtGui.QFont()
font.setPointSize(12)
font.setBold(True)
font.setWeight(75)
self.label.setFont(font)
self.label.setObjectName(("label"))
self.label.setText("SR")
self.label_2 = QtGui.QLabel(self)
self.label_2.setGeometry(QtCore.QRect(190, 25, 61, 21))
font = QtGui.QFont()
font.setPointSize(12)
font.setBold(True)
font.setWeight(75)
self.label_2.setFont(font)
self.label_2.setObjectName(("label_2"))
self.label_2.setText("Priority")
self.setTabOrder(self.lineEdit,self.spinBox)
self.setTabOrder(self.spinBox,self.textEdit)
self.lineEdit.setFocus(True)
self.setWindowTitle("Add To Do SR")
self.show()
## Button functions
QtCore.QObject.connect(self.buttonBox, QtCore.SIGNAL(("accepted()")), self.build)
QtCore.QObject.connect(self.buttonBox, QtCore.SIGNAL(("accepted()")), self.close)
QtCore.QObject.connect(self.buttonBox, QtCore.SIGNAL(("rejected()")), self.cancel)
def cancel(self):
self.close()
def save(self):
#self.close()
return self.d
def build(self):
#if(len(self.lineEdit.text()!=0)
#print len(self.lineEdit.text())
self.d["SR"]=str(unicode(self.lineEdit.text().toUtf8(), encoding="UTF-8"))
self.d["desc"]=str(unicode(self.textEdit.toPlainText().toUtf8(), encoding="UTF-8"))
self.d["p"]=str(self.spinBox.value())
#print self.d
if self.d["SR"]!='':
#print "saving"
f= open('todo.p', 'r+')
load=p.load(f)
f.close()
#print load
tmp2=[]
tmp2.append(self.d["desc"])
tmp2.append(self.d["p"])
tmp2.append(1)
load[self.d['SR']]=tmp2
#print tmp
#print load
f=open('todo.p','w')
p.dump(load,f)
f.close()
print "closed"
self.save
else:
self.d={}
return False
def openwindow():
app = QtGui.QApplication(sys.argv)
edit_params__QD = MyQDialog()
edit_params__QD.exec_()
edit_params__QD.activateWindow()
if edit_params__QD.result() == 0:
d= edit_params__QD.save()
if len(d)==0:
#print "did not add no SR num"
return False
print "exited out"
#sys.exit(app.exex_())