How can I by default have all text selected in my lineEdit? - pyqt

I'd like to be able to have all text highlighted in my lineEdit. However, the default selectAll() doesn't seem to do so.
import sys
from PyQt4 import QtCore, QtGui
from gui import Ui_Form
class MyForm(QtGui.QMainWindow):
def __init__(self, parent=None):
QtGui.QWidget.__init__(self, parent)
self.ui = Ui_Form()
self.ui.setupUi(self)
self.ui.lineEdit.setText("Type something here!")
self.ui.lineEdit.selectAll()
QtCore.QObject.connect(self.ui.pushButton, QtCore.SIGNAL("clicked()"), self.ui.textEdit.clear)
QtCore.QObject.connect(self.ui.lineEdit, QtCore.SIGNAL("returnPressed()"), self.add_entry)
def add_entry(self):
self.ui.lineEdit.selectAll()
self.ui.lineEdit.cut()
self.ui.textEdit.append("")
self.ui.textEdit.paste()
if __name__ == "__main__":
app = QtGui.QApplication(sys.argv)
myapp = MyForm()
myapp.show()
sys.exit(app.exec_())
I want to select the text on the lineEdit in the default constructor; however, it doesn't. Any reason for this? What should I be doing instead to accomplish this?

Related

Why does the label show only the last set image? (PyQt5) [duplicate]

I have got this problem. I´m trying to set text on a lineEdit object on pyqt4, then wait for a few seconds and changing the text of the same lineEdit. For this I´m using the time.sleep() function given on the python Time module. But my problem is that instead of setting the text, then waiting and finally rewrite the text on the lineEdit, it just waits the time it´s supposed to sleep and only shows the final text. My code is as follows:
from PyQt4 import QtGui
from gui import *
class Ventana(QtGui.QMainWindow, Ui_MainWindow):
def __init__(self, parent=None):
QtGui.QWidget.__init__(self, parent)
self.setupUi(self)
self.button.clicked.connect(self.testSleep)
def testSleep(self):
import time
self.lineEdit.setText('Start')
time.sleep(2)
self.lineEdit.setText('Stop')
def mainLoop(self, app ):
sys.exit( app.exec_())
if __name__ == '__main__':
import sys
app = QtGui.QApplication(sys.argv)
window = Ventana()
window.show()
sys.exit(app.exec_())
You can't use time.sleep here because that freezes the GUI thread, so the GUI will be completely frozen during this time.
You should probably use a QTimer and use it's timeout signal to schedule a signal for deferred delivery, or it's singleShot method.
For example (adapted your code to make it run without dependencies):
from PyQt4 import QtGui, QtCore
class Ventana(QtGui.QWidget):
def __init__(self, parent=None):
QtGui.QWidget.__init__(self, parent)
self.setLayout(QtGui.QVBoxLayout())
self.lineEdit = QtGui.QLineEdit(self)
self.button = QtGui.QPushButton('clickme', self)
self.layout().addWidget(self.lineEdit)
self.layout().addWidget(self.button)
self.button.clicked.connect(self.testSleep)
def testSleep(self):
self.lineEdit.setText('Start')
QtCore.QTimer.singleShot(2000, lambda: self.lineEdit.setText('End'))
def mainLoop(self, app ):
sys.exit( app.exec_())
if __name__ == '__main__':
import sys
app = QtGui.QApplication(sys.argv)
window = Ventana()
window.show()
sys.exit(app.exec_())
Also, take a look at the QThread sleep() function, it puts the current thread to sleep and allows other threads to run. https://doc.qt.io/qt-5/qthread.html#sleep
You can't use time.sleep here because that freezes the GUI thread, so the GUI will be completely frozen during this time.You can use QtTest module rather than time.sleep().
from PyQt4 import QtTest
QtTest.QTest.qWait(msecs)
So your code should look like:
from PyQt4 import QtGui,QtTest
from gui import *
class Ventana(QtGui.QMainWindow, Ui_MainWindow):
def __init__(self, parent=None):
QtGui.QWidget.__init__(self, parent)
self.setupUi(self)
self.button.clicked.connect(self.testSleep)
def testSleep(self):
import time
self.lineEdit.setText('Start')
QtTest.QTest.qWait(2000)
self.lineEdit.setText('Stop')
def mainLoop(self, app ):
sys.exit( app.exec_())
if __name__ == '__main__':
import sys
app = QtGui.QApplication(sys.argv)
window = Ventana()
window.show()
sys.exit(app.exec_())

PyQt5 program runs but does not display anything - widgets does not show [duplicate]

First of all, similar questions have been answered before, yet I need some help with this one.
I have a window which contains one button (Class First) and I want on pressed, a second blank window to be appeared (Class Second).
I fiddled with the code copied from this question: PyQT on click open new window, and I wrote this code:
# -*- coding: utf-8 -*-
from PyQt4 import QtGui, QtCore
import sys
import design1, design2
class Second(QtGui.QMainWindow, design2.Ui_MainWindow):
def __init__(self, parent=None):
super(Second, self).__init__(parent)
self.setupUi(self)
class First(QtGui.QMainWindow, design1.Ui_MainWindow):
def __init__(self, parent=None):
super(First, self).__init__(parent)
self.setupUi(self)
self.pushButton.clicked.connect(self.on_pushButton_clicked)
self.dialog = Second(self)
def on_pushButton_clicked(self):
self.dialog.exec_()
def main():
app = QtGui.QApplication(sys.argv)
main = First()
main.show()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
but on_pressed, this error message appears:
AttributeError: 'Second' object has no attribute 'exec_'
(design1 and design2 have been derived from the Qt designer.)
Any thought would be appreciated.
Here I'm using the show method.
Here is a working example (derived from yours):
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from PyQt4 import QtGui, QtCore
import sys
class Second(QtGui.QMainWindow):
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.pushButton = QtGui.QPushButton("click me")
self.setCentralWidget(self.pushButton)
self.pushButton.clicked.connect(self.on_pushButton_clicked)
self.dialog = Second(self)
def on_pushButton_clicked(self):
self.dialog.show()
def main():
app = QtGui.QApplication(sys.argv)
main = First()
main.show()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
If you need a new window every time you click the button, you can change the code that the dialog is created inside the on_pushButton_clicked method, like so:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from PyQt4 import QtGui, QtCore
import sys
class Second(QtGui.QMainWindow):
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.pushButton = QtGui.QPushButton("click me")
self.setCentralWidget(self.pushButton)
self.pushButton.clicked.connect(self.on_pushButton_clicked)
self.dialogs = list()
def on_pushButton_clicked(self):
dialog = Second(self)
self.dialogs.append(dialog)
dialog.show()
def main():
app = QtGui.QApplication(sys.argv)
main = First()
main.show()
sys.exit(app.exec_())
if __name__ == '__main__':
main()

Show sub window in main window

Can't work out how to embed a window in a main window using classes:
#!/usr/bin/python3
# -*- coding: utf-8 -*-
"""
Qt4 tutorial using classes
This example will be built
on over time.
"""
import sys
from PyQt4 import QtGui, QtCore
class Form(QtGui.QWidget):
def __init__(self, MainWindow):
super(Form, self).__init__()
class MainWindow(QtGui.QMainWindow):
def __init__(self, parent=None):
super(MainWindow, self).__init__()
self.setGeometry(50, 50, 1600, 900)
new_window = Form(self)
self.show()
def main():
app = QtGui.QApplication(sys.argv)
main_window = MainWindow()
sys.exit(app.exec_())
if __name__ == "__main__":
main()
This is supposed to be the single most basic bit of code using classes. How do I get the second window to show please.
As ekhumoro already pointed out, your widget needs to be a child of your mainWindow. However, I do not think that you need to call show for the widget, since it anyways gets called as soon as its parent (MainWindow) calls show. As mata pointed out correctly, the proper way to add a Widget to a MainWindow instance is to use setCentralWidget. Here is a working example for clarification:
import sys
from PyQt4 import QtGui, QtCore
class Form(QtGui.QWidget):
def __init__(self, parent):
super(Form, self).__init__(parent)
self.lbl = QtGui.QLabel("Test", self)
class MainWindow(QtGui.QMainWindow):
def __init__(self, parent=None):
super(MainWindow, self).__init__()
self.setGeometry(50, 50, 1600, 900)
new_window = Form(self)
self.setCentralWidget(new_window)
self.show()
def main():
app = QtGui.QApplication(sys.argv)
main_window = MainWindow()
sys.exit(app.exec_())
if __name__ == "__main__":
main()

populating combo box with folders on disk using QFileSystemModel

Hi I have written this basic code trying to populate folders underneath the /Users/ directory, but I don't know what I am missing its not populating.
import sys
from PyQt4 import QtGui
from PyQt4 import QtCore
class MyWindow(QtGui.QWidget):
"""docstring for MyWindow"""
def __init__(self, parent=None):
super(MyWindow, self).__init__()
self.setup()
def setup(self):
fsm = QtGui.QFileSystemModel()
fsm.setRootPath("/Users/")
layout = QtGui.QVBoxLayout()
combo = QtGui.QComboBox()
combo.setModel(fsm)
layout.addWidget(combo)
self.setLayout(layout)
def main():
app = QtGui.QApplication(sys.argv)
win = MyWindow()
win.show()
win.raise_()
sys.exit(app.exec_())
if __name__ == "__main__":
main()
I am getting a / in the comobobox instead of the whole list of folders under /Users/ directory.
I think its better to use QFileSystemModel instead of using os.listdir interms of efficiency and will update the view if somebody updates folder or adds folder in the /Users/ directory !
Remember that QFileSystemModel is a hierarchical model, so you need to let the QComboBox know which QModelIndex represents the children you want to display. You do that with QComboBox.setRootModelIndex()
QFileSystemModel.setRootPath() conveniently returns the QModelIndex of the path you set.
So a small change is all you need (tested on Windows) -
import sys
from PyQt4 import QtGui
from PyQt4 import QtCore
class MyWindow(QtGui.QWidget):
"""docstring for MyWindow"""
def __init__(self, parent=None):
super(MyWindow, self).__init__()
self.setup()
def setup(self):
fsm = QtGui.QFileSystemModel()
index = fsm.setRootPath("/Users/")
layout = QtGui.QVBoxLayout()
combo = QtGui.QComboBox()
combo.setModel(fsm)
combo.setRootModelIndex(index)
layout.addWidget(combo)
self.setLayout(layout)
def main():
app = QtGui.QApplication(sys.argv)
win = MyWindow()
win.show()
win.raise_()
sys.exit(app.exec_())
if __name__ == "__main__":
main()

How to avoid the child QMainWindow disappearing?

When I click the button, "ChildWindow" will flash and disappear. Then If I add the function exec_(), it will report an "AttributeError" because "QMainWindow" don't have this attribute.
How to modify the function "showChildWindow" so that it can work well? Thank you.
import sys
from PyQt4 import QtCore, QtGui
class MainWindow(QtGui.QMainWindow):
def __init__(self, parent=None):
QtGui.QWidget.__init__(self, parent)
self.setWindowTitle("MainWindow Window!")
self.setGeometry(400, 400, 100, 100)
self.centerWidget = QtGui.QWidget()
self.setCentralWidget(self.centerWidget)
self.pushButton = QtGui.QPushButton("&Button")
layout = QtGui.QVBoxLayout()
layout.addWidget(self.pushButton)
self.centerWidget.setLayout(layout)
class ChildWindow(QtGui.QMainWindow):
def __init__(self, parent=None):
QtGui.QWidget.__init__(self, parent)
self.setWindowTitle("Child Window!")
def showChildWindow():
mw = MainWindow()
child_win = ChildWindow(mw)
child_win.show()
#child_win.exec_() #AttributeError: 'ChildWindow' object has no attribute 'exec_'
if __name__ == "__main__":
app = QtGui.QApplication(sys.argv)
myapp = MainWindow()
myapp.show()
QtCore.QObject.connect(myapp.pushButton,QtCore.SIGNAL("clicked()"),showChildWindow)
sys.exit(app.exec_())
This program can work well.
import sys
from PyQt4 import QtCore, QtGui
class MainWindow(QtGui.QMainWindow):
def __init__(self, parent=None):
QtGui.QWidget.__init__(self, parent)
self.setWindowTitle("MainWindow Window!")
self.setGeometry(400, 400, 100, 100)
self.centerWidget = QtGui.QWidget()
self.setCentralWidget(self.centerWidget)
pushButton = QtGui.QPushButton("&Button")
layout = QtGui.QVBoxLayout()
layout.addWidget(pushButton)
self.centerWidget.setLayout(layout)
QtCore.QObject.connect(pushButton,QtCore.SIGNAL("clicked()"),self.showChildWindow)
def showChildWindow(self):
self.child_win = ChildWindow(self)
self.child_win.show()
class ChildWindow(QtGui.QMainWindow):
def __init__(self, parent=None):
QtGui.QWidget.__init__(self, parent)
self.setWindowTitle("Child Window!")
if __name__ == "__main__":
app = QtGui.QApplication(sys.argv)
myapp = MainWindow()
myapp.show()
sys.exit(app.exec_())
The real question appears to be: how do I access the main-window from other modules in my application?
My preferred general solution to this problem is to sub-class QApplication and add a simple accessor method, like this:
class Application(QtGui.QApplication):
def __init__(self):
QtGui.QApplication.__init__(self, sys.argv)
self._window = None
def window(self):
if self._window is None:
self._window = MainWindow()
return self._window
if __name__ == "__main__":
app = QtGui.qApp = Application()
app.window().show()
sys.exit(app.exec_())
With that in place, you can easily get access the methods of the main-window in other modules like this:
from PyQt4 import QtGui
QtGui.qApp.window().showChildWindow()
I had the same problem. The child QMainWindow would randomly disappear while interacting with the parent window.
This is the bad source code that causes this problem:
def showChildWindow(self):
child_win = ChildWindow()
child_win.show()
This is the good source code that fixes the problem:
def showChildWindow(self):
child_win = ChildWindow(self)
child_win.show()
When you instantiate the child window, make sure you pass the parent self.

Resources