How can I pass data in run method (thread) (python, Pyqt) - python

I want to make the thread, in the window, using PyQt(Python). For example
class window(QtGui.QWidget):
def __init__(self, parent = None):
QtGui.QWidget.__init__(self, parent)
self.setGeometry(100, 100, 500, 200)
self.setWindowTitle('Hello')
self.label = QtGui.QLabel(u'WoRLd', self)
self.Layout = QtGui.QVBoxLayout()
self.Layout.addWidget(self.label)
self.setLayout(self.Layout)
self.introduced = 123
self.request = Requests()
self.request.start()
self.connect(self.request, QtCore.SIGNAL("mysignal(QString)"),
self.on_change, QtCore.Qt.QueuedConnection)
def on_change(self, s):
self.label.setText(s)
class Requests():
def __init__(self, parent=None):
QtCore.QThread.__init__(self, parent)
def run(self):
self.emit(QtCore.SIGNAL("mysignal(QString)"), "143242" )
app = QtGui.QApplication(sys.argv)
main = window()
main.show()
sys.exit(app.exec_())
But, in method "run", I need some dates from "class window" (variable: introduced).
How can I pass this variable to "def run"?

you just have to make arguments for it and pass it into the class instance. then assign it to self.date, this makes it accesible across the class instance:
class window(QtGui.QWidget):
def __init__(self, parent = None):
QtGui.QWidget.__init__(self, parent)
self.setGeometry(100, 100, 500, 200)
self.setWindowTitle('Hello')
self.label = QtGui.QLabel(u'WoRLd', self)
self.Layout = QtGui.QVBoxLayout()
self.Layout.addWidget(self.label)
self.setLayout(self.Layout)
self.introduced = 123
date = # get some date whatever you need to pass here
self.request = Requests(date)
self.request.start()
self.connect(self.request, QtCore.SIGNAL("mysignal(QString)"),
self.on_change, QtCore.Qt.QueuedConnection)
def on_change(self, s):
self.label.setText(s)
class Requests():
def __init__(self, date, parent=None):
self.date = date
QtCore.QThread.__init__(self, parent)
def run(self):
# do something with self.date here
self.emit(QtCore.SIGNAL("mysignal(QString)"), "143242" )
app = QtGui.QApplication(sys.argv)
main = window()
main.show()
sys.exit(app.exec_())

Related

PyQT: Exit/Complete Second Window Before First Window

I have the following code below:
from PyQt4 import QtGui
import sys
class Second(QtGui.QWidget):
def __init__(self, parent=None):
super(Second, self).__init__(parent)
self.grid = QtGui.QGridLayout(self)
self.setGeometry(650,400,400,200)
self.widget = QtGui.QWidget()
class First(QtGui.QMainWindow):
def __init__(self, parent=None):
super(First, self).__init__(parent)
self.grid = QtGui.QGridLayout(self)
self.setGeometry(350, 200, 1000, 700)
self.widget = QtGui.QWidget()
Button1 = QtGui.QPushButton('...', self)
Button1.clicked.connect(self.on_pushButton_clicked)
self.grid.addWidget(Button1, 0, 0, 1, 1)
def on_pushButton_clicked(self):
self.Second = Second()
self.Second.setWindowTitle('Window')
self.Second.show()
def main():
app = QtGui.QApplication(sys.argv)
main = First()
main.show()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
When I click the button, I want to be able to finish up my action in the second window before continuing on the first. Right now, I can exit out of my first window and the second window remains open. How do you keep on the second window but keep the first window unselectable?
There are 2 possible solutions:
- Second must inherit from QDialog, pass it as parent to the first window and use exec_() instead of show:
class Second(QtGui.QDialog):
def __init__(self, parent=None):
super(Second, self).__init__(parent)
class First(QtGui.QMainWindow):
def __init__(self, parent=None):
super(First, self).__init__(parent)
self.setGeometry(350, 200, 1000, 700)
self.widget = QtGui.QWidget()
self.setCentralWidget(self.widget)
grid = QtGui.QGridLayout(self.widget)
Button1 = QtGui.QPushButton('...', self)
Button1.clicked.connect(self.on_pushButton_clicked)
grid.addWidget(Button1, 0, 0, 1, 1)
#QtCore.pyqtSlot()
def on_pushButton_clicked(self):
self.Second = Second(self)
self.Second.setWindowTitle('Window')
self.Second.exec_()
- Change the windowModality to Qt::WindowModal, activate the flag Qt::Dialog and pass it the first window as parent.
class Second(QtGui.QWidget):
def __init__(self, parent=None):
super(Second, self).__init__(parent)
self.setWindowModality(QtCore.Qt.WindowModal)
self.setWindowFlags(self.windowFlags() | QtCore.Qt.Dialog)
class First(QtGui.QMainWindow):
def __init__(self, parent=None):
super(First, self).__init__(parent)
self.setGeometry(350, 200, 1000, 700)
self.widget = QtGui.QWidget()
self.setCentralWidget(self.widget)
grid = QtGui.QGridLayout(self.widget)
Button1 = QtGui.QPushButton('...', self)
Button1.clicked.connect(self.on_pushButton_clicked)
grid.addWidget(Button1, 0, 0, 1, 1)
#QtCore.pyqtSlot()
def on_pushButton_clicked(self):
self.Second = Second(self)
self.Second.setWindowTitle('Window')
self.Second.show()

giving index to QLineEdit

i want to give index for QLineEdit's.
i have this code.
from PyQt4 import QtGui, QtCore
import sys
class Main(QtGui.QMainWindow):
def __init__(self, parent = None):
super(Main, self).__init__(parent)
# main button
self.addButton = QtGui.QPushButton('button to add other widgets')
self.addButton.clicked.connect(self.addWidget)
self.savebutton = QtGui.QPushButton('Save')
# scroll area widget contents - layout
self.scrollLayout = QtGui.QFormLayout()
# scroll area widget contents
self.scrollWidget = QtGui.QWidget()
self.scrollWidget.setLayout(self.scrollLayout)
# scroll area
self.scrollArea = QtGui.QScrollArea()
self.scrollArea.setWidgetResizable(True)
self.scrollArea.setWidget(self.scrollWidget)
# main layout
self.mainLayout = QtGui.QVBoxLayout()
# add all main to the main vLayout
self.mainLayout.addWidget(self.addButton)
self.mainLayout.addWidget(self.scrollArea)
self.mainLayout.addWidget(self.savebutton)
# central widget
self.centralWidget = QtGui.QWidget()
self.centralWidget.setLayout(self.mainLayout)
# set central widget
self.setCentralWidget(self.centralWidget)
def addWidget(self):
self.scrollLayout.addRow(Test())
class Test(QtGui.QWidget):
def __init__( self, parent=None):
super(Test, self).__init__(parent)
self.kod = QtGui.QLineEdit()
layout = QtGui.QHBoxLayout()
layout.addWidget(self.kod)
self.setLayout(layout)
app = QtGui.QApplication(sys.argv)
myWidget = Main()
myWidget.show()
app.exec_()
when i clicked save button, savebutton sends just last QLineEdit widget.
image is here
like in this photo, i want self.kod[0].text()="aaaa" self.kod1="bbbb" self.kod[2]="cccc" and it just will go like this. kod[x] this x number will increase automatically, while i click add widgetbutton. or it can be like this: kod1,kod2,kod3, kodx. it doesnt matter, i want to just differ from eacht other and take text from them.
You can set a list in Main class, like this ['aaa', 'bbb', 'ccc'],
and set a var = 0.
class Main(QtGui.QMainWindow):
def __init__(self, parent = None):
super(Main, self).__init__(parent)
#
self.lineText = ['aaa', 'bbb', 'ccc']
self.var = 0
...
def addWidget(self):
self.scrollLayout.addRow(Test(self, self.var))
self.var += 1
Then give Test class an arg,
class Test(QtGui.QWidget):
def __init__( self, parent=None, count):
super(Test, self).__init__(parent)
#
self.parent = parent
self.kod = QtGui.QLineEdit()
#
self.kod.setText(self.parent.lineText[count])
---
class Main(QtGui.QMainWindow):
def __init__(self, parent = None):
super(Main, self).__init__(parent)
self.kod = []
...
def addWidget(self):
temp = Test()
self.kod.append(temp)
self.scrollLayout.addRow(temp)
and print(self.kod)
[<__main__.Test object at 0x00000000032EEC18>, <__main__.Test object at 0x00000000032EEDC8>, <__main__.Test object at 0x00000000032EEF78>]

placing widget in tab causes bug which disables controls - python

I noticed when placing a widget inside of a tab control it disables all the functions of the drag-n-drop? Why would this be? You can clearly see in the TreeWidget I'm enabling drag and drop functionalities...? I'm confused. I can no longer drag and drop my qtreewidget items.
# Imports
# ------------------------------------------------------------------------------
import sys
from PySide import QtGui, QtCore
class TreeNodeItem( QtGui.QTreeWidgetItem ):
def __init__( self, parent, name="" ):
super( TreeNodeItem, self ).__init__( parent )
self.setText( 0, name )
self.stuff = "Custom Names - " + str(name)
class TreeWidget(QtGui.QTreeWidget):
def __init__(self, parent=None):
QtGui.QTreeWidget.__init__(self, parent)
self.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOn)
self.setSelectionMode(QtGui.QAbstractItemView.ExtendedSelection)
self.setItemsExpandable(True)
self.setAnimated(True)
self.setDragEnabled(True)
self.setDropIndicatorShown(True)
self.setDragDropMode(QtGui.QAbstractItemView.InternalMove)
self.setAlternatingRowColors(True)
# Drag-n-Drop Widget
# ------------------------------------------------------------------------------
class ExampleWidget(QtGui.QWidget):
def __init__(self,):
super(ExampleWidget, self).__init__()
self.initUI()
def initUI(self):
# formatting
self.resize(250, 400)
self.setWindowTitle("Example")
# widget - passes treewidget
self.itemList = QtGui.QTreeWidget()
self.itemList = TreeWidget()
headers = [ "Items" ]
self.itemList.setColumnCount( len(headers) )
self.itemList.setHeaderLabels( headers )
# layout Grid - row/column/verticalpan/horizontalspan
self.mainLayout = QtGui.QGridLayout(self)
self.mainLayout.setContentsMargins(5,5,5,5)
self.mainLayout.addWidget(self.itemList, 0,0,1,1)
# display
self.show()
# Functions
# --------------------------------------------------------------------------
def showEvent(self, event):
print "open"
for i in xrange(20):
TreeNodeItem( parent=self.itemList , name=str(i) )
class Example(QtGui.QWidget):
def __init__(self):
super(Example, self).__init__()
self.initUI()
def initUI(self):
# formatting
self.resize(550, 400)
# widgets
tab_panel = QtGui.QTabWidget()
_tab = QtGui.QWidget()
_tab_layout = QtGui.QHBoxLayout(_tab)
_tab_layout.addWidget(ExampleWidget())
tab_panel.addTab(_tab, "Testing")
# signals
tab_panel.currentChanged.connect(self.Update)
# main layout
main_layout = QtGui.QVBoxLayout()
main_layout.addWidget(tab_panel)
self.setLayout(main_layout)
self.show()
def Update(self):
print "update"
# self.adjustSize()
def main():
app = QtGui.QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
Fixed incorrect widget nesting as well as the show event.
# Imports
# ------------------------------------------------------------------------------
import sys
from PySide import QtGui, QtCore
class TreeNodeItem( QtGui.QTreeWidgetItem ):
def __init__( self, parent, name="" ):
super( TreeNodeItem, self ).__init__( parent )
self.setText( 0, name )
self.stuff = "Custom Names - " + str(name)
class TreeWidget(QtGui.QTreeWidget):
def __init__(self, parent=None):
QtGui.QTreeWidget.__init__(self, parent)
self.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOn)
self.setSelectionMode(QtGui.QAbstractItemView.ExtendedSelection)
self.setItemsExpandable(True)
self.setAnimated(True)
self.setDragEnabled(True)
self.setDropIndicatorShown(True)
self.setDragDropMode(QtGui.QAbstractItemView.InternalMove)
self.setAlternatingRowColors(True)
# Drag-n-Drop Widget
# ------------------------------------------------------------------------------
class ExampleWidget(QtGui.QWidget):
def __init__(self,):
super(ExampleWidget, self).__init__()
self.initUI()
def initUI(self):
# formatting
self.resize(250, 400)
self.setWindowTitle("Example")
# widget - passes treewidget
self.itemList = QtGui.QTreeWidget()
self.itemList = TreeWidget()
headers = [ "Items" ]
self.itemList.setColumnCount( len(headers) )
self.itemList.setHeaderLabels( headers )
# layout Grid - row/column/verticalpan/horizontalspan
self.mainLayout = QtGui.QGridLayout(self)
self.mainLayout.setContentsMargins(5,5,5,5)
self.mainLayout.addWidget(self.itemList, 0,0,1,1)
# Functions
# --------------------------------------------------------------------------
def showEvent(self, event):
print "open"
for i in xrange(20):
TreeNodeItem( parent=self.itemList , name=str(i) )
class Example(QtGui.QWidget):
def __init__(self):
super(Example, self).__init__()
self.initUI()
def initUI(self):
# formatting
self.resize(550, 400)
tab_panel = QtGui.QTabWidget()
tab_panel.addTab(ExampleWidget(), "Test Tab")
mainLayout = QtGui.QVBoxLayout()
mainLayout.addWidget(tab_panel)
self.setLayout(mainLayout)
def Update(self):
print "update"
# self.adjustSize()
def main():
app = QtGui.QApplication(sys.argv)
ex = Example()
ex.show()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
# I think it was a table widget in another widget that then got placed in a tab widget.
# Maybe another level too.
# You were also initializing something in the args part of a method.

How do i open a class from within another class by selecting an item on ToolBar?? Python/PyQt

I am trying to run class AddTQuestions from a def in class AddTest but it wont work!! It opens the window AddTQuestions for a split-second then closes it straight away?!
The code is shown here:
import sys
from PyQt4 import QtCore, QtGui
class Example(QtGui.QMainWindow):
def __init__(self):
super(Example, self).__init__()
self.initUI()
def initUI(self):
RunClassAction = QtGui.QAction(QtGui.QIcon('exit24.png'), 'Exit', self)
RunClassAction.triggered.connect(self.run)
self.toolbar = self.addToolBar('Exit')
self.toolbar.addAction(RunClassAction)
self.setGeometry(300, 300, 300, 200)
self.setWindowTitle('Why Wont this Woooorkkkkk')
self.show()
def run(self):
AddQuestion = AddTQuestions()
AddQuestion.show()
class AddTQuestions(QtGui.QMainWindow):
def __init__(self, parent=None):
super(AddTQuestions, self).__init__(parent)
self.welldone = QtGui.QLabel('WellDone')
self.button = QtGui.QPushButton('Press Me')
layout = QtGui.QVBoxLayout()
layout.addWidget(self.welldone)
layout.addWidget(self.button)
self.setLayout(layout)
print("hello")
if __name__ == '__main__':
app = QtGui.QApplication([])
window = Example()
window.show()
app.exec_()
The object get's garbage collected, since you don't hold any reference to it when the function ends.
add them as class variables like this and the window stays open.
self.AddQuestion = AddTQuestions()
self.AddQuestion.show()

Qt and python - how to refer to another class

I have main window which contains scene and button in widget from where I need to call scene:
import sys
from PySide.QtCore import *
from PySide.QtGui import *
class Widget(QWidget):
def __init__(self, scene):
super(Widget, self).__init__()
self.refreshButton = QPushButton("Refresh", self)
self.refreshButton.clicked.connect(self.Refresh)
# THIS ACTION SHOULD PROCEED ARGUMENTS
# TO FUNCION "Refresh"
layout = QHBoxLayout()
layout.addWidget(self.refreshButton)
self.setLayout(layout)
self.show()
def Refresh(self, scene):
mainWinScene = scene
print "On Refresh! - ", mainWinScene.items()
class MainScene(QGraphicsScene):
def __init__(self):
super(MainScene, self).__init__()
class MainWindow(QMainWindow):
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
self.scene = MainScene()
self.scene.setSceneRect(0,0,200,100)
self.scene.addLine(20,10,150,80)
self.view = QGraphicsView()
self.view.setScene(self.scene)
drawRectAct = QAction('&Add Rectangle', self)
drawRectAct.triggered.connect(self.drawRect)
shapeInspectorAct = QAction('&Show Inspector', self)
shapeInspectorAct.triggered.connect(self.showInspector)
menubar = self.menuBar()
fileMenu = menubar.addMenu('&Shapes')
fileMenu.addAction(drawRectAct)
fileMenu.addAction(shapeInspectorAct)
self.setCentralWidget(self.view)
def drawRect(self):
self.scene.addRect(50,50,20,30)
def showInspector(self):
self.I = Widget(self.scene)
if __name__ == '__main__':
app = QApplication(sys.argv)
main = MainWindow()
main.show()
sys.exit(app.exec_())
How to proceed "scene" argument with action - to "Refresh" function?
You can pass a scene in Widget's constructor:
class Widget(QWidget):
def __init__(self, scene):
...
self.scene = scene
...
def Refresh(self):
print "On Refresh! - ", self.scene.items()
class MainWindow(QMainWindow):
...
def showInspector(self):
self.I = Widget(self.scene)
...

Categories