I'm trying to set the focus on QLineEdit widget at app startup but for some reasons it fails. Calling the method which includes the QLineEdit_object.setFocus() and is bound to a button click, works perfectly. However on startup, it seems like it doesn't execute at all when set to initialize after widget creation.
Using PySide with Python.
# coding=utf-8
import sys
import PySide.QtGui as QG
import PySide.QtCore as QC
class GG(QG.QMainWindow):
def __init__(self):
super(GG, self).__init__()
self.move(0,0)
self.resize(400,300)
self.setWindowTitle('Demo')
self.tabw = QG.QTabWidget()
self.tab1 = Tab1()
self.tab2 = Tab2()
self.tabw.addTab(self.tab1, 'Tab1')
self.tabw.addTab(self.tab2, 'Tab2')
hbox = QG.QHBoxLayout()
hbox.addWidget(self.tabw)
self.setCentralWidget(self.tabw)
self.setLayout(hbox)
self.show()
class Tab1(QG.QWidget):
def __init__(self):
super(Tab1, self).__init__()
self.btns()
self.inputt()
self.layoutz()
self.inp.setFocus() # doesn't set the focus on startup ?
self.show()
def inputt(self):
self.inp = QG.QLineEdit('', self)
def btns(self):
self.btn1 = QG.QPushButton('Button1', self)
self.btn1.clicked.connect(self.focusit) # works just fine
def layoutz(self):
vbox = QG.QVBoxLayout()
vbox.addWidget(self.btn1)
vbox.addStretch(1)
vbox.addWidget(self.inp)
self.setLayout(vbox)
def focusit(self):
self.inp.setFocus() # works just fine
class Tab2(Tab1):
def __init__(self):
super(Tab2, self).__init__()
def main():
app = QG.QApplication(sys.argv)
a = GG()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
Well, after some playing I came up with this solution:
import sys
import PySide.QtGui as QG
import PySide.QtCore as QC
class GG(QG.QMainWindow):
def __init__(self):
super(GG, self).__init__()
self.move(0,0)
self.resize(400,300)
self.setWindowTitle('Demo')
self.tabw = QG.QTabWidget()
self.tab1 = Tab1()
self.tab2 = Tab2()
self.tabw.addTab(self.tab1, 'Tab1')
self.tabw.addTab(self.tab2, 'Tab2')
hbox = QG.QHBoxLayout()
hbox.addWidget(self.tabw)
self.setCentralWidget(self.tabw)
self.setLayout(hbox)
self.tab2.inp.setFocus() # setting focus right here
self.tab1.inp.setFocus() # and here; notice the order
self.show()
class Tab1(QG.QWidget):
def __init__(self):
super(Tab1, self).__init__()
self.btns()
self.inputt()
self.layoutz()
self.show()
def inputt(self):
self.inp = QG.QLineEdit('', self)
def btns(self):
self.btn1 = QG.QPushButton('Button1', self)
self.btn1.clicked.connect(self.focusit)
def layoutz(self):
vbox = QG.QVBoxLayout()
vbox.addWidget(self.btn1)
vbox.addStretch(1)
vbox.addWidget(self.inp)
self.setLayout(vbox)
def focusit(self):
self.inp.setFocus()
class Tab2(Tab1):
def __init__(self):
super(Tab2, self).__init__()
def main():
app = QG.QApplication(sys.argv)
a = GG()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
Related
Every time the user clicks on an item in QTreeWidget, the computer starts to perform some heavy duty tasks. My only objective is to use QThread to prevent freeze.
Consider the following code:
from PyQt5.QtWidgets import*
from PyQt5.QtCore import*
import time
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle('MainWindow')
self.layout = QVBoxLayout()
self.treewidget = MyTreeWidget()
self.treewidget.itemClicked.connect(self.tree_click)
self.layout.addWidget(self.treewidget)
self.label = QLabel("Label", self)
self.layout.addWidget(self.label)
widget = QWidget()
widget.setLayout(self.layout)
self.setCentralWidget(widget)
self.show()
#pyqtSlot(QTreeWidgetItem)
def tree_click(self, item):
time.sleep(2)
self.label.setText(item.text(0))
class MyTreeWidget(QTreeWidget):
def __init__(self):
super().__init__()
item_1 = QTreeWidgetItem()
item_1.setText(0, 'one item')
item_2 = QTreeWidgetItem()
item_2.setText(0,'another item')
self.addTopLevelItem(item_1)
item_1.addChild(item_2)
self.setHeaderHidden(True)
if __name__ == '__main__':
import sys
app = QApplication(sys.argv)
main = MainWindow()
app.exec()
How to modify the above code to prevent freeze and what is the most appropriate way of doing it?
I tried by following the protocol given in Background thread with QThread in PyQt, the second answer:
from PyQt5.QtWidgets import*
from PyQt5.QtCore import*
import time
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle('MainWindow')
self.layout = QVBoxLayout()
self.treewidget = MyTreeWidget()
self.treewidget.itemClicked.connect(self.tree_click)
self.layout.addWidget(self.treewidget)
self.label = QLabel("Label", self)
self.layout.addWidget(self.label)
widget = QWidget()
widget.setLayout(self.layout)
self.setCentralWidget(widget)
self.show()
#pyqtSlot(QTreeWidgetItem)
def tree_click(self, item):
self.obj = Worker()
self.thread = QThread()
self.obj.finished.connect(self.change_text)
self.obj.moveToThread(self.thread)
self.obj.finished.connect(self.thread.quit)
self.thread.started.connect(self.obj.work)
self.thread.start()
def change_text(self):
self.label.setText(item.text(0))
class Worker(QObject):
finished = pyqtSignal()
#pyqtSlot()
def work(self):
time.sleep(2)
finished = pyqtSignal()
class MyTreeWidget(QTreeWidget):
def __init__(self):
super().__init__()
item_1 = QTreeWidgetItem()
item_1.setText(0, 'one item')
item_2 = QTreeWidgetItem()
item_2.setText(0,'another item')
self.addTopLevelItem(item_1)
item_1.addChild(item_2)
self.setHeaderHidden(True)
if __name__ == '__main__':
import sys
app = QApplication(sys.argv)
main = MainWindow()
app.exec()
It does not look like I am doing the right thing.
I made a couple of minor adjustments to make your worker class run properly. This will prevent the rest of the gui from freezing but the label text that depends on the long running process will continue to take that long to update.
Also if the task implemented in the separate thread is repeated frequently you may want to consider using a QThreadPool.
I also included some inline comments to explain some of the changes.
from PyQt5.QtWidgets import*
from PyQt5.QtCore import*
import time
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle('MainWindow')
self.layout = QVBoxLayout()
self.treewidget = MyTreeWidget()
self.treewidget.itemClicked.connect(self.tree_click)
self.layout.addWidget(self.treewidget)
self.label = QLabel("Label", self)
self.layout.addWidget(self.label)
widget = QWidget()
widget.setLayout(self.layout)
self.setCentralWidget(widget)
self.show()
self.threads = [] # make shift threads container
#pyqtSlot(QTreeWidgetItem)
def tree_click(self, item):
self.obj = Worker()
thread = QThread()
self.obj.text = item.text(0) # the obj needs a copy of the text to emit
self.obj.textReady.connect(self.change_text)
self.obj.moveToThread(thread)
self.obj.finished.connect(thread.quit)
thread.finished.connect(thread.deleteLater) # delete the threads once finished
thread.started.connect(self.obj.work)
thread.start()
self.threads.append(thread)
def change_text(self, text):
self.label.setText(text)
class Worker(QObject):
finished = pyqtSignal()
textReady = pyqtSignal([str])
#pyqtSlot()
def work(self):
time.sleep(2)
self.textReady.emit(self.text) # emit the text that needs to be changed
self.finished.emit()
class MyTreeWidget(QTreeWidget):
def __init__(self):
super().__init__()
item_1 = QTreeWidgetItem()
item_1.setText(0, 'one item')
item_2 = QTreeWidgetItem()
item_2.setText(0,'another item')
self.addTopLevelItem(item_1)
item_1.addChild(item_2)
self.setHeaderHidden(True)
if __name__ == '__main__':
import sys
app = QApplication(sys.argv)
main = MainWindow()
app.exec()
I'm trying to write a system test for my project. I have a controller class which launches the various windows. However, I can't seem to control windows launch using exec with the qtbot.
Here is an MVCE:
from PyQt5.QtWidgets import *
from PyQt5 import QtGui
class Controller:
def __init__(self):
self.name = None
self.a = WindowA(self)
def launchB(self):
self.b = WindowB(self)
if self.b.exec_():
self.name = self.b.getData()
class WindowA(QDialog):
def __init__(self, controller):
super(WindowA, self).__init__()
self.controller = controller
layout = QVBoxLayout()
self.button = QPushButton('Launch B')
self.button.clicked.connect(self.controller.launchB)
layout.addWidget(self.button)
self.setLayout(layout)
self.show()
class WindowB(QDialog):
def __init__(self, controller):
super(WindowB, self).__init__()
self.controller = controller
layout = QVBoxLayout()
self.le = QLineEdit()
self.button = QPushButton('Save')
self.button.clicked.connect(self.save)
layout.addWidget(self.le)
layout.addWidget(self.button)
self.setLayout(layout)
self.show()
def getData(self):
return self.le.text()
def save(self):
if self.le.text():
self.accept()
self.close()
else:
self.reject()
from PyQt5.QtWidgets import QApplication
if __name__ == '__main__':
import sys
app = QApplication(sys.argv)
window = Controller()
sys.exit(app.exec_())
I'd like to test that the user successfully enters data in the lineedit. In my test I'm able to successfully click the button in WindowA to launch WindowB, but am unable to use keyClicks to enter data in the lineedit.
Here is the test:
def test_1(qtbot):
control = Controller()
qtbot.mouseClick(control.a.button, QtCore.Qt.LeftButton)
qtbot.keyClicks(control.b.le, 'Test_Project')
qtbot.mouseClick(control.b.button, QtCore.Qt.LeftButton)
assert control.name == 'Test_Project'
The problem is that using exec_() blocks all synchronous tasks until the window is closed, the solution is to use a QTimer to launch the remaining tasks asynchronously:
def test_1(qtbot):
control = Controller()
def on_timeout():
qtbot.keyClicks(control.b.le, "Test_Project")
qtbot.mouseClick(control.b.button, QtCore.Qt.LeftButton)
QtCore.QTimer.singleShot(0, on_timeout)
qtbot.mouseClick(control.a.button, QtCore.Qt.LeftButton)
assert control.name == "Test_Project"
When I run the code below my program crashes, and I believe this is to-do with the .text() called when the Line edit has something typed in it. I need to assign a variable to what is entered here.
import sys
from PyQt5.QtWidgets import *
from PyQt5 import QtWidgets
class loginScreen(QtWidgets.QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
usernameBox = QtWidgets.QLineEdit()
usernameBox.textChanged.connect(self.myfunc)
vArrangement = QtWidgets.QVBoxLayout()
vArrangement.addWidget(usernameBox)
self.setLayout(vArrangement)
self.show()
def myfunc(self):
x = usernameBox.text()
print(x)
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = loginScreen()
sys.exit(app.exec_())
If you observe usernameBox it is created as a local variable so it can not be accessed by the other methods of the class, in your case there are 2 solutions:
Make a usernameBox attribute of the class.
class loginScreen(QtWidgets.QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
self.usernameBox = QtWidgets.QLineEdit()
self.usernameBox.textChanged.connect(self.myfunc)
vArrangement = QtWidgets.QVBoxLayout()
vArrangement.addWidget(self.usernameBox)
self.setLayout(vArrangement)
self.show()
def myfunc(self):
x = self.usernameBox.text()
print(x)
Or use sender() that obtains the object that emits the signal, in your case the QLineEdit.
class loginScreen(QtWidgets.QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
usernameBox = QtWidgets.QLineEdit()
usernameBox.textChanged.connect(self.myfunc)
vArrangement = QtWidgets.QVBoxLayout()
vArrangement.addWidget(usernameBox)
self.setLayout(vArrangement)
self.show()
def myfunc(self):
x = self.sender().text()
print(x)
class Window(QtGui.QMainWindow):
def __init__(self):
super(Window, self).__init__()
self.tabs()
def home(self):
df = QtGui.QPushButton('hello', self)
df.show()
def series(self):
df = QtGui.QCheckBox('hello', self)
df.show()
def tabs(self):
btn_home = QtGui.QPushButton(QtGui.QIcon('home.png'), 'Home', self)
btn_home.clicked.connect(self.home)
btn_series = QtGui.QPushButton(QtGui.QIcon('series.png'),'Series', self)
btn_series.clicked.connect(self.series)
self.show()
def run():
app = QtGui.QApplication(sys.argv)
GUI = Window()
sys.exit(app.exec_())
if __name__ == '__main__': run()
I wanted to delete the widgets shown from home module when i click series button and delete widgets from series module when i click home button.
So far whats happening is when i click series button he previous widgets from home module are still there.
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
import sys
class Window(QMainWindow):
def __init__(self):
super(Window, self).__init__()
self.widget =QWidget()
self.layout = QHBoxLayout()
self.widget.setLayout(self.layout)
self.setCentralWidget(self.widget)
self.tabs()
def home(self):
self.clear()
self.df1 = QPushButton('hello')
self.layout.addWidget(self.df1)
def series(self):
self.clear()
self.df2 = QCheckBox('hello')
self.layout.addWidget(self.df2)
def tabs(self):
self.btn_home = QPushButton(QIcon('home.png'), 'Home')
self.btn_home.clicked.connect(self.home)
self.layout.addWidget(self.btn_home)
self.btn_series = QPushButton(QIcon('series.png'),'Series')
self.btn_series.clicked.connect(self.series)
self.layout.addWidget(self.btn_series)
self.show()
def clear(self):
item = self.layout.itemAt(2)
if item != None :
widget = item.widget()
if widget != None:
self.layout.removeWidget(widget)
widget.deleteLater()
def run():
app = QApplication(sys.argv)
GUI = Window()
sys.exit(app.exec_())
if __name__ == '__main__': run()
My version is
self.main_canvas.children().remove(cogmapui)
cogmapui.deleteLater()
I checked it by putting a print("Deleted") in the cogmapui's __del__ function and, yes, it gets called.
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()