Here is my Code. I want to capture a pressed key and print it. But Nothing will Happen, How to resolve it? I Have two classes. One is Create_Instance and another one is Main_Window. In My code, I have Only Lable items to display. How to activate it?
Edited
import sys
from PyQt5.QtWidgets import *
class Create_Instance(QWidget):
def __init__(self,dict_item):
super().__init__()
self.dict_items = dict_item
self.lbl = QLabel("This is My Label")
self.vbox = QVBoxLayout()
self.vbox.addWidget(self.lbl)
self.setLayout(self.vbox)
def keyPressEvent(self, event):
print(event)
print(self.dict_items)
class Main_Window(QWidget):
def __init__(self):
super(). __init__()
self.setWindowTitle("Main Window")
self.layout_main = QHBoxLayout()
self.firstmenu_container = Create_Instance(dict_item="1")
self.secondmenu_container = Create_Instance(dict_item="2")
self.layout_main.addWidget(self.firstmenu_container)
self.layout_main.addWidget(self.secondmenu_container)
self.setLayout(self.layout_main)
def main():
app = QApplication(sys.argv)
ex = Main_Window()
ex.show()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
You must add the widget to the layout:
def __init__(self):
super().__init__()
self.setWindowTitle("Main Window")
self.layout_main = QHBoxLayout()
self.firstmenu_container = Create_Instance(dict_item="1")
self.layout_main.addWidget(self.firstmenu_container)
self.secondmenu_container = Create_Instance(dict_item="2")
self.layout_main.addWidget(self.secondmenu_container)
self.setLayout(self.layout_main)
Related
I have a Qt widget that looks like this:
class launchiiwidget(QtWidgets.QWidget):
def __init__(self):
super().__init__()
layout = QtWidgets.QVBoxLayout(self)
self.textbox = QtWidgets.QTextEdit(self)
self.textbox.setLineWrapMode(QtWidgets.QTextEdit.NoWrap)
self.textbox.setAlignment(QtCore.Qt.AlignCenter)
self.textbox.setFixedSize(QtCore.QSize(600, 100))
self.textbox.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
self.textbox.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
layout.addWidget(self.textbox)
font = self.textbox.font()
font.setPointSize(80)
self.textbox.setFont(font)
self.listwidget = QtWidgets.QListWidget(self)
self.listwidget.addItem("Red")
self.listwidget.addItem("Blue")
layout.addWidget(self.listwidget)
if __name__ == "__main__":
app = QtWidgets.QApplication([])
widget = launchiiwidget()
widget.setWindowFlags(QtCore.Qt.FramelessWindowHint)
widget.resize(600, 200)
widget.show()
sys.exit(app.exec())
How can I make it so when the "return" or "right arrow key" is pressed, focus moves from wherever it is currently to the first item in listwidget? This should also work while being focused inside of textbox, without triggering a newline.
Note: items get dynamically added to listwidget.
A possible solution could be to use QShorcut but because the OP requires "without triggering a newline". So in this case the solution is to implement an eventfilter to the QWindow:
import sys
from PyQt6 import QtCore, QtGui, QtWidgets
class KeyHelper(QtCore.QObject):
pressed = QtCore.pyqtSignal()
def __init__(self, window):
super().__init__(window)
self._window = window
self.window.installEventFilter(self)
#property
def window(self):
return self._window
def eventFilter(self, obj, event):
if event.type() == QtCore.QEvent.Type.KeyPress:
if event.key() in (
QtCore.Qt.Key.Key_Return,
QtCore.Qt.Key.Key_Enter,
QtCore.Qt.Key.Key_Right,
):
self.pressed.emit()
return True
return super().eventFilter(obj, event)
class Launchiiwidget(QtWidgets.QWidget):
def __init__(self):
super().__init__()
self.textbox = QtWidgets.QTextEdit()
self.textbox.setLineWrapMode(QtWidgets.QTextEdit.LineWrapMode.NoWrap)
self.textbox.setAlignment(QtCore.Qt.AlignmentFlag.AlignCenter)
self.textbox.setFixedSize(QtCore.QSize(600, 100))
self.textbox.setVerticalScrollBarPolicy(
QtCore.Qt.ScrollBarPolicy.ScrollBarAlwaysOff
)
self.textbox.setHorizontalScrollBarPolicy(
QtCore.Qt.ScrollBarPolicy.ScrollBarAlwaysOff
)
font = self.textbox.font()
font.setPointSize(80)
self.textbox.setFont(font)
self.listwidget = QtWidgets.QListWidget()
self.listwidget.addItem("Red")
self.listwidget.addItem("Blue")
layout = QtWidgets.QVBoxLayout(self)
layout.addWidget(self.textbox)
layout.addWidget(self.listwidget)
def update_focus(self):
self.listwidget.setFocus()
index = self.listwidget.model().index(0, 0)
if index.isValid():
self.listwidget.setCurrentIndex(index)
if __name__ == "__main__":
app = QtWidgets.QApplication([])
widget = Launchiiwidget()
widget.setWindowFlags(QtCore.Qt.WindowType.FramelessWindowHint)
widget.resize(600, 200)
widget.show()
key_helper = KeyHelper(widget.windowHandle())
key_helper.pressed.connect(widget.update_focus)
sys.exit(app.exec())
There is this QLineEdit with setText is set to a predefined value and there is a QDialog with QLabel in it which is supposed to show whatever is in the QLineEdit. The code below shows the situation.
import sys
import os
import datetime
from PySide2.QtWidgets import *
from PySide2 import *
now = datetime.datetime.now()
now_str = now.strftime("%H.%M.%S,%d/%m/%y")
default_text = (str("Sugar_" + now_str))
class MainWindow(QWidget):
def __init__(self):
super(MainWindow, self).__init__()
self.resize(600, 500)
btn = QPushButton("show dialog")
mw_layout = QVBoxLayout()
mw_layout.addWidget(btn)
self.setLayout(mw_layout)
btn.clicked.connect(show_d)
class dialog(QDialog):
def __init__(self):
super(dialog, self).__init__()
self.resize(400, 350)
title = QLineEdit()
title.setText(default_text)
show_title = QPushButton("Show title")
cancel = QPushButton("Cancel")
d_layout = QVBoxLayout()
d_layout.addWidget(title)
d_layout.addWidget(show_title)
d_layout.addWidget(cancel)
self.setLayout(d_layout)
t = title.text()
title_dialog = QDialog()
label = QLabel()
label.setText("The title is " + title.text())
ok = QPushButton("OK!")
t_layout = QVBoxLayout()
t_layout.addWidget(label)
t_layout.addWidget(ok)
title_dialog.setLayout(t_layout)
def show_t():
title_dialog.exec_()
title_dialog.setModal(True)
def close_t():
title_dialog.accept()
show_title.clicked.connect(show_t)
ok.clicked.connect(close_t)
cancel.clicked.connect(self.close_d)
def close_d(self):
self.reject()
def show_d():
d = dialog()
d.exec_()
d.setModal(True)
if __name__ == '__main__':
app = QApplication(sys.argv)
MainWindow = MainWindow()
MainWindow.show()
sys.exit(app.exec_())
But this doesn't work like I expected it to. The QLabel text just show the default text even when the text in QLineEdit is changed.
The console also shows the following error;
qt.xkb.compose: failed to create compose table.
I think there is something's obviously wrong but I can't seem to find what.
Any help appreciated.
You must update the text before a certain event, for example an instant before displaying the dialog:
class dialog(QDialog):
def __init__(self):
super(dialog, self).__init__()
self.resize(400, 350)
self.title_lineedit = QLineEdit(default_text)
show_title = QPushButton("Show title")
cancel = QPushButton("Cancel")
d_layout = QVBoxLayout(self)
d_layout.addWidget(self.title_lineedit)
d_layout.addWidget(show_title)
d_layout.addWidget(cancel)
self.title_dialog = QDialog()
self._title_label = QLabel()
ok = QPushButton("OK!")
t_layout = QVBoxLayout(self.title_dialog)
t_layout.addWidget(self._title_label)
t_layout.addWidget(ok)
show_title.clicked.connect(self.on_clicked)
ok.clicked.connect(self.title_dialog.reject)
cancel.clicked.connect(self.reject)
self.update_label()
def update_label(self):
self._title_label.setText("The title is " + self.title_lineedit.text())
def on_clicked(self):
self.update_label()
self.title_dialog.exec_()
This question already has answers here:
Variable scopes in Python classes
(4 answers)
Closed 3 years ago.
I am making an addressbook on PyQt5 and can't make the window be shown completely because it is shown only once.
I know that the problem occurs because I am trying to initiate the class when the button is clicked, but it's the only way I've came up with to uptade the QLabel text, otherwise the window will be shown without any text on it.
Here is some code:
from PyQt5 import QtWidgets
class Window(QtWidgets.QWidget):
def __init__(self):
QtWidgets.QWidget.__init__(self)
self.resize(400,200)
self.show()
self.text = ''
self.button = QtWidgets.QPushButton('Show')
self.box = QtWidgets.QVBoxLayout()
self.box.addWidget(self.button)
self.setLayout(self.box)
self.button.clicked.connect(self.init)
def init(self):
self.text = 'Text'
win2 = AppearWindow()
win2.show()
class AppearWindow(QtWidgets.QWidget):
def __init__(self):
QtWidgets.QWidget.__init__(self)
self.resize(100, 50)
self.label = QtWidgets.QLabel()
self.label.setText(win.text)
self.box = QtWidgets.QVBoxLayout()
self.box.addWidget(self.label)
self.setLayout(self.box)
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
win = Window()
sys.exit(app.exec_())
How can I make AppearWindow be shown if I want the QLabel text on it be updated when the button on the main window is clicked?
Try it:
from PyQt5 import QtWidgets
import random
class Window(QtWidgets.QWidget):
def __init__(self):
super().__init__()
self.text = ''
self.button = QtWidgets.QPushButton('Show')
self.button.clicked.connect(self.init)
self.box = QtWidgets.QVBoxLayout()
self.box.addWidget(self.button)
self.setLayout(self.box)
def init(self):
self.text = random.choice(['Text1', 'Text2', 'Text3'])
self.win2 = AppearWindow(self.text) # + self
self.win2.show() # + self
class AppearWindow(QtWidgets.QWidget):
def __init__(self, text):
QtWidgets.QWidget.__init__(self)
self.resize(100, 50)
self.label = QtWidgets.QLabel()
# self.label.setText(win.text)
self.label.setText(text)
self.box = QtWidgets.QVBoxLayout()
self.box.addWidget(self.label)
self.setLayout(self.box)
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
win = Window()
win.resize(400,200)
win.show()
sys.exit(app.exec_())
I want show text after enter key pressed
from PyQt5.QtWidgets import QWidget, QApplication, QPlainTextEdit, QVBoxLayout, QLabel
from PyQt5.QtCore import Qt
import sys
class PlainTextEdit(QPlainTextEdit):
def __init__(self, parent):
super().__init__(parent=parent)
close_window = ClosingWindow()
vbox = QVBoxLayout()
self.close_window.setLayout(vbox)
def keyPressEvent(self, QKeyEvent):
if QKeyEvent.key() == Qt.Key_Enter:
self.close_window.label_display.setText("Enter key pressed")
class ClosingWindow(QWidget):
def __init__(self):
super().__init__()
plainText = PlainTextEdit(self)
self.initUI()
def initUI(self):
vbox = QVBoxLayout()
label_display = QLabel("Text Here")
self.setLayout(vbox)
self.setWindowTitle("Message Box")
self.setGeometry(200, 200, 500, 300)
self.show()
if __name__ == "__main__":
app = QApplication(sys.argv)
close_win = ClosingWindow()
sys.exit(app.exec_())
Your code has the following errors:
You are creating an infinite loop: You are creating a PlainTextEdit within a ClosingWindow, and in that PlainTextEdit you are creating another ClosingWindow, and in that other ClosingWindow you are creating a PlainTextEdit, etc. Every time you use the constructor of a class you are creating a different object, so the "close_window" created in PlainTextEdit is different from the "close_win".
Each class must have a single responsibility (1), in your case the responsibility of PlainTextEdit is to notify that it was pressed enter, and in that case you must use a signal.
The enter key on the keyboard does not correspond to Qt::Key_Enter but Qt::Key_Return, it only corresponds to Qt::Key_Return on the keypad.
It is not necessary to create a layout in PlainTextEdit.
Considering the above, the solution is:
from PyQt5 import QtCore, QtWidgets
class PlainTextEdit(QtWidgets.QPlainTextEdit):
sendTextSignal = QtCore.pyqtSignal(str)
def keyPressEvent(self, event):
if event.key() in (QtCore.Qt.Key_Enter, QtCore.Qt.Key_Return):
self.sendTextSignal.emit("Enter key pressed")
else:
self.sendTextSignal.emit("Not Enter key pressed")
super().keyPressEvent(event)
class ClosingWindow(QtWidgets.QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
plainText = PlainTextEdit()
label_display = QtWidgets.QLabel("Text Here")
plainText.sendTextSignal.connect(label_display.setText)
vbox = QtWidgets.QVBoxLayout(self)
vbox.addWidget(plainText)
vbox.addWidget(label_display)
self.setWindowTitle("Message Box")
self.setGeometry(200, 200, 500, 300)
self.show()
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
close_win = ClosingWindow()
sys.exit(app.exec_())
(1) Single responsibility principle
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.