Keep menu open after clicking on the button it is launched with - python

I have a QToolButton with a menu. When the QToolButton is clicked, the menu appears. The default behavior is that when an action is clicked from the menu, the menu disappears. How can I make it so that the menu stays open until the user clicks elsewhere?
Here is minimal code that shows the behavior:
from PyQt4 import QtGui, QtCore
import sys, os
if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
toolButton = QtGui.QToolButton()
toolButton.setText('Select')
toolMenu = QtGui.QMenu()
for i in range(3):
action = toolMenu.addAction(str(i))
action.setCheckable(True)
toolButton.setMenu(toolMenu)
toolButton.setPopupMode(QtGui.QToolButton.InstantPopup)
toolButton.show()
sys.exit(app.exec_())

Shamelessly porting this code from this c++ answer:
from PyQt4 import QtGui, QtCore
import sys, os
if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
toolButton = QtGui.QToolButton()
toolButton.setText('Select')
toolMenu = QtGui.QMenu()
for i in range(3):
checkBox = QtGui.QCheckBox(str(i), toolMenu)
checkableAction = QtGui.QWidgetAction(toolMenu)
checkableAction.setDefaultWidget(checkBox)
toolMenu.addAction(checkableAction)
toolButton.setMenu(toolMenu)
toolButton.setPopupMode(QtGui.QToolButton.InstantPopup)
toolButton.show()
sys.exit(app.exec_())

I made a PyQt5 version based on #three_pineapples's answer and solved what #Space Hornet tried to solve--get the states of checkboxes.
According to the doc of QWidgetAction:
Note that it is up to the widget to activate the action, for example
by reimplementing mouse event handlers and calling QAction::trigger().
So I think one needs to connect the checkbox's stateChanged signal to the action's trigger method.
I also added the a text to the action therefore action.text() gives the same text label as the checkbox. May not be necessary though.
Complete code below:
import sys
from PyQt5 import QtWidgets
from PyQt5.QtCore import pyqtSlot
#pyqtSlot(QtWidgets.QAction)
def menuTriggered(action):
print('state change=',action.text())
return
#pyqtSlot(QtWidgets.QMenu)
def buttonTriggered(menu):
actions=menu.findChildren(QtWidgets.QWidgetAction)
for actii in actions:
wii=actii.defaultWidget()
stateii=wii.isChecked()
print('action', actii.text(), 'is checked:',stateii)
return
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
toolButton = QtWidgets.QToolButton()
toolButton.setText('Select')
toolMenu = QtWidgets.QMenu()
for i in range(3):
checkBox = QtWidgets.QCheckBox(str(i), toolMenu)
checkableAction = QtWidgets.QWidgetAction(toolMenu)
checkableAction.setDefaultWidget(checkBox)
# Add a text to action, for easier handling in slot
checkableAction.setText(str(i))
# Connect the checkbox's stateChanged to QAction.trigger
checkBox.stateChanged.connect(checkableAction.trigger)
toolMenu.addAction(checkableAction)
toolMenu.triggered.connect(menuTriggered)
toolButton.setMenu(toolMenu)
toolButton.setPopupMode(QtWidgets.QToolButton.MenuButtonPopup)
# NOTE that toolButton.clicked work, toolButton.triggered not
toolButton.clicked.connect(lambda: buttonTriggered(toolMenu))
toolButton.show()
sys.exit(app.exec_())

The easiest solution I've managed to find is to make an addition to actionEvent:
class myMenu(QtGui.QMenu):
def actionEvent(self, event):
super().actionEvent(event)
self.show()

I was looking for the exact same thing and used the code from three_pineapples, but I had trouble connecting it the way I wanted. I thought I'd share my solution in case anyone else finds it useful.
The button function is very similar but my code includes my solution for connecting the checkboxes to a function. Also, since they are stored in a list one can connect them individually or in a loop if that's easier.
from PyQt4.QtCore import *
from PyQt4.QtGui import *
import sys, os
##### main window class #####
class main_window(QMainWindow):
def __init__(self):
super(main_window, self).__init__()
self.resize(300, 200)
wdgMain = QWidget()
self.setCentralWidget(wdgMain)
layMain = QGridLayout(wdgMain)
wdgMain.setLayout(layMain)
## checkable tool button ##
tlbToolButton1 = QToolButtonChx("Check Me Out!")
layMain.addWidget(tlbToolButton1, 0, 0)
tlbToolButton1.addItems(["Item" + str(n) for n in range(8)])
## connect tool button checkboxes ##
for i in range(tlbToolButton1.length()):
tlbToolButton1.index(i).stateChanged.connect(self.checkbox_tester)
def checkbox_tester(self, choice):
objSender = self.sender()
strObjectName = objSender.objectName()
print "Action Checker::", strObjectName, ":", choice
##### end of main window class #####
##### checkable tool button class #####
class QToolButtonChx(QToolButton):
def __init__(self, strText=""):
super(QToolButtonChx, self).__init__()
self.setText(strText)
tlbMenu = QMenu(self)
self.setMenu(tlbMenu)
self.setPopupMode(QToolButton.MenuButtonPopup)
self.lstchxItems = []
def addItem(self, strItem):
self.lstchxItems.append(QCheckBox(strItem, self.menu()))
actCheckItem = QWidgetAction(self.menu())
actCheckItem.setDefaultWidget(self.lstchxItems[-1])
self.lstchxItems[-1].setObjectName('chx' + strItem)
self.menu().addAction(actCheckItem)
def addItems(self, lstItems):
for strItem in lstItems:
self.lstchxItems.append(QCheckBox(strItem, self.menu()))
actCheckItem = QWidgetAction(self.menu())
actCheckItem.setDefaultWidget(self.lstchxItems[-1])
self.lstchxItems[-1].setObjectName('chx' + strItem)
self.menu().addAction(actCheckItem)
def index(self, intIndex):
return self.lstchxItems[intIndex]
def length(self):
return len(self.lstchxItems)
##### end of checkable tool button class #####
if __name__ == '__main__':
app = QApplication(sys.argv)
winMain = QMainWindow()
gui = main_window()
gui.show()
sys.exit(app.exec_())

Related

Python, first window crash until another function its executed

I want my program to show another window where it says that it's the break time when the determined requirements are met (in this case the exact same hour) but when I run it, the first window (not the login one) crashes or simply doesn't show up until it is the hour.
(horatime and min can be changed for testing it)
main and main2 are windows programed in PyCharm they are clocks.
I want to show main window until the time set in the code ("timecheck") is reached then "timecheck" will hide main and show main2
this is my code:
'''
from PyQt5 import QtWidgets, uic
from PyQt5.QtWidgets import QApplication, QMainWindow
from PyQt5.QtCore import QTimer, QTime
from PyQt5.uic import loadUi
import datetime
app = QtWidgets.QApplication([])
login = uic.loadUi("ventana1.ui")
time = uic.loadUi("ventana2.ui")
error = uic.loadUi("ventana3.ui")
def gui_login():
name = login.lineEdit.text()
password = login.lineEdit_2.text()
if len(name)==0 or len(password)==0:
login.label_5.setText("Ingrese todos los datos")
elif name == "Pedro" and password == "1234":
gui_clock()
timecheck()
else:
gui_error()
def gui_clock():
login.hide()
main.show()
def timecheck():
horatime = int(19)
min = int(21)
while True:
if horatime == datetime.datetime.now().hour and min == datetime.datetime.now().minute:
main.hide()
main2.show()
break
#this is the clock1, it shows the time in red
class VentanaPrincipal(QMainWindow):
def __init__(self):
super(VentanaPrincipal, self).__init__()
loadUi('ventana2.ui', self)
timer = QTimer(self)
timer.timeout.connect(self.displayTime)
timer.start(1000)
def displayTime(self):
currentTime = QTime.currentTime()
displayText = currentTime.toString('hh:mm:ss')
self.reloj.setText(displayText)
self.lcdNumber.display(displayText)
#this is the clock2, it shows the time in green
class VentanaPrincipal2(QMainWindow):
def __init__(self2):
super(VentanaPrincipal2, self2).__init__()
loadUi('ventana4.ui', self2)
timer2 = QTimer(self2)
timer2.timeout.connect(self2.displayTime)
timer2.start(1000)
def displayTime(self):
currentTime2 = QTime.currentTime()
displayText2 = currentTime2.toString('hh:mm:ss')
self.reloj.setText(displayText2)
self.lcdNumber.display(displayText2)
def gui_error():
login.hide()
error.show()
def back_error():
error.hide()
login.show()
login.pushButton.clicked.connect(gui_login)
error.pushButton.clicked.connect(regresar_error)
login.show()
main = VentanaPrincipal()
main2 = VentanaPrincipal2()
app.exec()
i tried a lot of things to change the loop to show what i want, but im just an amateur on programming so i cant find a way to make my programm to do what i want

How can I detect when one window occludes another in PyQt5?

I'm using PyQt5 to create an app with multiple main windows. I want to be able to allow the user to save and load window sizes and window positions. That's easy with, e.g., QMainWindow.saveGeometry() and QMainWindow.loadGeometry() or the corresponding .saveState() and .loadState() variants. These work great for position and size, but if the user moves or resizes one window so that it occludes another, I want to also restore this positioning. I don't mind writing my own code to save the info for each window, but I can't see any way to detect the relative Z order of windows. Am I missing it in the docs, or is this not possible?
To see what I mean, try this:
from PyQt5.QtWidgets import QApplication, QMainWindow, QPlainTextEdit
from PyQt5.QtCore import QSettings
from PyQt5.QtGui import QCloseEvent
'''
context: Linux Mint 19.3 Tricia x86_64
Python 3.9
PyQt5 5.15.1
'''
class RememberWin(QMainWindow):
def __init__(self, win_name: str):
super(RememberWin, self).__init__()
self.win_name = win_name
self.setWindowTitle(win_name)
self.can_close = False
def restore_window(self) -> bool:
try:
settings = QSettings("PyQtExamples", "RememberWinTest")
self.restoreGeometry(settings.value(f'{self.win_name} Geometry'))
self.restoreState(settings.value(f'{self.win_name} State'))
return True
except:
return False
def closeEvent(self, event: QCloseEvent):
if not self.can_close:
event.ignore()
else:
settings = QSettings("PyQtExamples", "RememberWinTest")
settings.setValue(f'{self.win_name} Geometry', self.saveGeometry())
settings.setValue(f'{self.win_name} State', self.saveState())
QMainWindow.closeEvent(self, event)
class ControlWindow(RememberWin):
def __init__(self, win_name: str = "ControlWindow"):
super(ControlWindow, self).__init__(win_name=win_name)
self.can_close = True
self.window1 = RememberWin(win_name='WindowOne')
self.window2 = RememberWin(win_name='WindowTwo')
self.text = QPlainTextEdit(self)
s = "Try making Window1 wide enough to cover Window2.\n" \
"Then close this window (auto closes others).\n" \
"Re-run the app and you'll notice that Window2\n" \
"is not on top of Window1 which means that this\n" \
"info isn't getting saved."
self.text.setPlainText(s)
self.setCentralWidget(self.text)
if not self.restore_window():
self.setGeometry(100, 390, 512, 100)
if not self.window1.restore_window():
self.window1.setGeometry(100, 100, 512, 384)
if not self.window2.restore_window():
self.window2.setGeometry(622, 100, 512, 384)
self.window1.show()
self.window2.show()
def closeEvent(self, event: QCloseEvent):
for win in (self.window1, self.window2):
win.can_close = True
win.close()
super(ControlWindow, self).closeEvent(event)
if __name__ == '__main__':
import sys
app = QApplication(sys.argv)
window = ControlWindow(win_name='ControlWindow (You can only close this one)')
window.show()
sys.exit(app.exec_())
The simplest way to do what you want to achieve is to keep track of the current focused widget, or, to be precise, the top level window of the last focused widget.
You can store the focused windows in the settings as a list, using a unique objectName for each window (you are already doing this, so you just need to use setObjectName()), then restore the window by showing them in the correct order as long as the object name matches.
class RememberWin(QMainWindow):
def __init__(self, win_name: str):
super(RememberWin, self).__init__()
self.win_name = win_name
self.setObjectName(win_name)
self.setWindowTitle(win_name)
self.can_close = False
# ...
class ControlWindow(RememberWin):
def __init__(self, win_name: str = "ControlWindow"):
# ...
self.settings = QSettings("PyQtExamples", "RememberWinTest")
self.zOrder = []
QApplication.instance().focusObjectChanged.connect(self.focusChanged)
windowOrder = self.settings.value('windowOrder', type='QStringList')
topLevelWindows = QApplication.topLevelWidgets()
if windowOrder:
for objName in windowOrder:
for win in topLevelWindows:
if win.objectName() == objName:
win.show()
else:
self.window1.show()
self.window2.show()
def focusChanged(self, obj):
if not obj or obj.window() == self.window():
return
if obj.window() in self.zOrder[:-1]:
self.zOrder.remove(obj.window())
self.zOrder.append(obj.window())
def closeEvent(self, event: QCloseEvent):
for win in (self.window1, self.window2):
win.can_close = True
win.close()
self.settings.setValue('windowOrder',
[w.window().objectName() for w in self.zOrder])
super(ControlWindow, self).closeEvent(event)

PyQT clicked.connect() action. Huge amount of button to one destiny, and multiple (iteration) of function

Is it possible to make shorter code? I have 40 buttons: 20 route to one page of widget, next 20 route to another page... But each button triggered other action (opening a file, with iterated name of file: prog1.txt, prog2.txt, prog3.txt, etc...
self.ui.prog_btn_1.clicked.connect(self.show_job_program_page)
self.ui.prog_btn_1.clicked.connect(self.click_prog1)
self.ui.prog_btn_2.clicked.connect(self.show_job_program_page)
self.ui.prog_btn_2.clicked.connect(self.click_prog2)
self.ui.prog_btn_3.clicked.connect(self.show_job_program_page)
self.ui.prog_btn_3.clicked.connect(self.click_prog3)
# Etc...
I'll make something like this:
If you click button prog_btn_1, open file prog1.txt, I want to avoid duplication of iterated name of functions and files.
You can have a look at something like this for inspiration. I don't know how the rest of the code looks so I put some checkboxes to illustrate it:
import sys
from PyQt5 import QtWidgets as qtw
class MainWindow(qtw.QWidget):
def __init__(self):
super().__init__()
self.setLayout(qtw.QVBoxLayout())
self.checkbox_dict = dict()
self.button_dict = dict()
for i in range(0, 10):
checkbox = qtw.QCheckBox(self, text='Checkbox' + str(i))
self.layout().addWidget(checkbox)
self.checkbox_dict[i] = checkbox
button = qtw.QPushButton(self, text='PushButton' + str(i))
self.layout().addWidget(button)
self.button_dict[i] = button
for i, button in enumerate(self.button_dict.values()):
button.clicked.connect(lambda _, i=i: self.click_checkbox(i))
self.show()
def click_checkbox(self, i):
self.checkbox = self.checkbox_dict[i]
self.checkbox_state = self.checkbox.isChecked()
self.checkbox.setChecked(not self.checkbox_state)
if __name__ == '__main__':
app = qtw.QApplication(sys.argv)
w = MainWindow()
sys.exit(app.exec())
Also check this thread for explanations for the lambda function

Why doesn't QTreeView.scrollTo() work initially

The code below just displays a tree view of computer drives. Each time a new file/folder is selected, the view scrolls to make this new selection visible.
Question 1: While this works, the initial selection after the application is launched doesn't trigger the scroll. Why?
Question 2: If the instructions:
self.my_view.scrollTo(index, QAbstractItemView.EnsureVisible)
self.my_view.resizeColumnToContents(0)
are inverted:
self.my_view.resizeColumnToContents(0)
self.my_view.scrollTo(index, QAbstractItemView.EnsureVisible)
the first column size is not adjusted either on the initial display, only after. Why?
import sys
from PyQt5.QtCore import Qt, QModelIndex, QDir
from PyQt5.QtWidgets import QApplication, QTreeView, QMainWindow, QFileSystemModel, QAbstractItemView
class MyWindow(QMainWindow):
def __init__(self):
super().__init__()
# Instance variables
self.my_view = QTreeView()
self.my_model = QFileSystemModel()
# Init FS model to show all computer drives
model_root_path = str(self.my_model.myComputer())
self.my_model.setRootPath(model_root_path)
# Init tree view
self.my_view.setModel(self.my_model)
self.my_view.setRootIndex(self.my_model.index(model_root_path))
self.my_view.setSelectionMode(QAbstractItemView.SingleSelection)
self.my_view.setSelectionBehavior(QAbstractItemView.SelectRows)
# Connect selection change events to custom slot
select_model = self.my_view.selectionModel()
select_model.currentRowChanged.connect(self.current_row_changed)
# Main window
self.setCentralWidget(self.my_view)
self.setGeometry(200, 200, 800, 600)
# Select initial row on view
focus_path = QDir.currentPath()
focus_index = self.my_model.index(focus_path)
self.my_view.setCurrentIndex(focus_index)
def current_row_changed(self):
"""Current row of the model has changed"""
# Scroll view to new row
index = self.my_view.selectionModel().currentIndex()
self.my_view.scrollTo(index, QAbstractItemView.EnsureVisible)
self.my_view.resizeColumnToContents(0)
# Show path of current row in window title
absolute_path = self.my_model.filePath(index)
self.setWindowTitle(absolute_path)
def main():
a = QApplication(sys.argv)
mw = MyWindow()
mw.show()
sys.exit(a.exec_())
if __name__ == '__main__':
main()
`
Edit: After using the good solution provided by #ekhumoro, my sample code above worked. However this other piece of code still didn't:
import os
import sys
from PyQt5.QtCore import pyqtSignal, QTimer, QDir, Qt
from PyQt5.QtWidgets import QMainWindow, QGridLayout, QWidget, QTreeView, QAbstractItemView, QFileSystemModel, \
QApplication
class AppWindow(QMainWindow):
default_folder_path = "."
def __init__(self):
super().__init__()
self.folder_view = FolderTreeView()
self.folder_view.folder_has_changed.connect(self.folder_changed)
self.build_ui()
self.show()
# Select initial folder
self.select_initial_folder()
def build_ui(self):
main_widget = QWidget()
layout = QGridLayout(main_widget)
layout.addWidget(self.folder_view)
self.setCentralWidget(main_widget)
self.setGeometry(200, 100, 800, 600)
def select_initial_folder(self):
folder_index = self.folder_view.get_index(AppWindow.default_folder_path)
if folder_index.isValid():
self.folder_view.select_folder(folder_index)
def folder_changed(self, folder_path):
if not os.path.isdir(folder_path):
print("Non existing folder:", folder_path)
return
class FolderTreeView(QTreeView):
folder_has_changed = pyqtSignal(str)
def __init__(self):
super().__init__()
self.folder_tree_model = FolderTreeModel()
self.setModel(self.folder_tree_model)
self.setSelectionMode(QAbstractItemView.SingleSelection)
self.setSelectionBehavior(QAbstractItemView.SelectRows)
def select_folder(self, folder_index):
self.setCurrentIndex(folder_index)
def currentChanged(self, current, previous):
super(FolderTreeView, self).currentChanged(current, previous)
# Scroll the view to current item and resize folder name column
QTimer.singleShot(50, lambda: self.delayed_scroll(current))
# Emit signal for other uses
self.folder_has_changed.emit(self.folder_tree_model.filePath(current))
def delayed_scroll(self, index):
self.scrollTo(index, QAbstractItemView.EnsureVisible)
self.resizeColumnToContents(0)
def get_index(self, folder_path):
return self.folder_tree_model.index(folder_path)
class FolderTreeModel(QFileSystemModel):
def __init__(self):
super().__init__()
self.setFilter(QDir.AllDirs | QDir.NoDotAndDotDot)
self.setRootPath("")
def main():
app = QApplication(sys.argv)
window = AppWindow()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
The first problem may be caused if, by default, the model initialises its current index to the current directory. This would mean that if you set it again to the same index, the row-change signal will not be emitted (because nothing changed). This can be fixed by calling the row-change handler directly:
class MyWindow(QMainWindow):
def __init__(self):
super().__init__()
...
focus_path = QDir.currentPath()
focus_index = self.my_model.index(focus_path)
self.my_view.setCurrentIndex(focus_index)
self.current_row_changed()
def current_row_changed(self):
index = self.my_view.currentIndex()
self.my_view.scrollTo(index, QAbstractItemView.EnsureVisible)
self.my_view.resizeColumnToContents(0)
...
As to the second problem: when you call scrollTo, it may have to expand several directories in order to select the required index. This could obviously change the width of the first column, so you should always call resizeColumnToContents afterwards in order to get the correct width.
UPDATE:
I think there is also another problem caused by timing issues. The QFileSystemModel must work asynchronously to some extent, because it has to request resources from the operating system and then wait for the response. Also, before it gets the response, it cannot know in advance exactly how much data it is going to receive, because the file-system may have been updated while it was waiting. Potentially, the response could include data from a huge directory containing thousands of files. So in order to keep the GUI responsive, the data is processed in batches which are of a sufficient size to fill the current view. If the current index is set before the window has been shown and all its widgets fully laid out, there is no guarantee that the view will be able to resize its columns correctly.
This can be fixed by explicitly re-calling the row-change handler via a one-shot timer with a small delay. This should allow the view to recalculate its column widths correctly:
...
focus_path = QDir.currentPath()
focus_index = self.my_model.index(focus_path)
self.my_view.setCurrentIndex(focus_index)
QTimer.singleShot(50, self.current_row_changed)
def current_row_changed(self):
index = self.my_view.currentIndex()
self.my_view.scrollTo(index, QAbstractItemView.EnsureVisible)
self.my_view.resizeColumnToContents(0)

PySide QWidget immediate update

In my application, I have a call to an external module which spawns some threads, does some stuff, then returns a value. I'm trying to get a QMessageBox to show before and a QLabel to update after this is complete, but I'm stumped. The code goes something like this (called from QObject.connect on a button):
def _process(self):
self._message_box.show()
for i in range(3):
rv = external_module_function_with_threads() // blocking function call
label = getattr(self, "label%d" % (i + 1))
label.setText(rv)
When I click the button and the function is called, the message box only shows after the loop completes. The labels only update after the loop completes as well. I tried calling label.repaint() in the loop, but all that seems to do is make the message box show up earlier (but with no text in it).
I know I'm not violating the "GUI operations from outside the main thread" rule (...right?), so is there a way to force an update?
For your message box use self._message_box.exec_(). From my understanding of your question, I think this will do what you want.
from PySide.QtCore import *
from PySide.QtGui import *
import sys
import time
class Main(QWidget):
def __init__(self, parent=None):
super(Main, self).__init__(parent)
layout = QVBoxLayout(self)
button = QPushButton("Press me")
self.label = QLabel("Run #")
map(layout.addWidget, [button, self.label])
button.pressed.connect(self.buttonPressed)
self.messageBox = QMessageBox()
def buttonPressed(self):
self.messageBox.exec_()
Thread().run(self.label)
class Thread(QThread):
def run(self, label):
for x in range(5):
self.updateLabel(label)
app.processEvents()
time.sleep(.5)
def updateLabel(self, label):
try:
number = int(label.text().split(" ")[-1])
number += 1
except ValueError:
number = 0
label.setText("Run %i" % number)
app = QApplication([])
main = Main()
main.show()
sys.exit(app.exec_())

Categories

Resources