PyQt6 Custom Dialog Content Not Appearing - python

When I run this code in my program, I expect to see an edit dialog when I click on the 'Edit Record' button. Instead, it shows me a blank dialog.
Code:
class EditDialog(QDialog):
def __init__(self):
super().__init__()
self.setWindowTitle('Edit Record')
self.setFixedSize(300, 300)
layout = QVBoxLayout()
index = main_window.table.currentRow()
student_name = main_window.table.item(index, 1).text()
self.student_name = QLineEdit(student_name)
self.student_name.setPlaceholderText('Student Name')
layout.addWidget(self.student_name)
course = main_window.table.item(index, 2).text()
self.student_course = QComboBox()
courses = ["Biology", "Math", "Astronomy", "Physics"]
self.student_course.addItems(courses)
self.student_course.setCurrentText(course)
layout.addWidget(self.student_course)
phone = main_window.table.item(index, 3).text()
self.student_phone = QLineEdit(phone)
self.student_phone.setPlaceholderText('Student Phone Number')
layout.addWidget(self.student_phone)
button = QPushButton('Edit Record')
button.clicked.connect(self.edit_student)
layout.addWidget(button)
Here is the contextual code:
#staticmethod
def edit():
edit_dialog = EditDialog()
edit_dialog.exec()
I wanted to see the edit GUI, but instead, I got a blank screen. Can someone tell me what is wrong with my code. Image of output screen

Don't forget
self.setLayout(layout)
at the end of your init method.

Related

How to make QCompletter shown description in QTextEdit beside

I'm using PyQt, trying to make QLineEdit field, that's have QCompletter and it's work. But i want that when user choose words from Completter widget it's shown a description right from Completter. I think its look so
I created a Qwidget class that have Hlayout wtih Qcompletter and QTextEdit inside. But when i run my code QtextEdit show in new window, not near with Completer.
class Custom_Completer(QWidget):
completer = None
describe = None
lb = None
def __init__(self):
super().__init__()
self.completer = QCompleter([])
self.describe = QTextEdit()
self.completer.setCaseSensitivity(Qt.CaseInsensitive)
self.completer.setCompletionMode(QCompleter.PopupCompletion)
self.completer.setMaxVisibleItems(10)
self.completer.highlighted.connect(self._highlited)
self.completer.activated.connect(self._activated)
self.describe.setReadOnly(True)
self.describe.setObjectName('autoCompeteInfoFrame')
self.describe.setFixedWidth(200)
self.describe.setLineWrapMode(QTextEdit.WidgetWidth)
self.describe.setText('Description here')
self.lb = QHBoxLayout()
self.lb.addWidget(self.completer.widget())
self.lb.addWidget(self.describe)
self.setLayout(self.lb)
def _highlited(self):
self.describe.show()
self.show()
print('highlited show QTextEdit')
def _activated(self):
self.describe.hide()
print('activated QTextEdit in description')
def main():
completer = Custom_Completer()
completer.setModel(['500', '5000','500000'])
line_edit.setCompleter(completer.completer)

Using 3 Buttons in PyQt5 DialogButtonBox

I'm attempting to create a Login System type dialog box for practice using PyQt5 (I'm quite new to the module) and i'm trying to give the user the ability to click (Ok, Cancel, Apply) as the buttons underneath inputs boxes for Username / Password, but i'm not sure how I can actually get the apply button to work. I have buttons.accepted.connect(*method*) and buttons.rejected.connect(*method*) but I don't know how to specify the pressing of the accept button. I have tried using buttons.clicked(dlgButtons[0] (Which is where the button is stored) but it just gives me an error.
The code below is my declaration of the buttons if that helps. Thanks
buttons = qt.QDialogButtonBox()
dlgButtons = (qt.QDialogButtonBox.Apply, qt.QDialogButtonBox.Ok, qt.QDialogButtonBox.Cancel)
buttons.setStandardButtons(
dlgButtons[0] | dlgButtons[1] | dlgButtons[2]
)
One possible solution might look like this:
from PyQt5.QtWidgets import *
class ModelessDialog(QDialog):
def __init__(self, part, threshold, parent=None):
super().__init__(parent)
self.setWindowTitle("Baseline")
self.setGeometry(800, 275, 300, 200)
self.part = part
self.threshold = threshold
self.threshNew = 4.4
label = QLabel("Part : {}\nThreshold : {}".format(
self.part, self.threshold))
self.label2 = QLabel("ThreshNew : {:,.2f}".format(self.threshNew))
self.spinBox = QDoubleSpinBox()
self.spinBox.setMinimum(-2.3)
self.spinBox.setMaximum(99)
self.spinBox.setValue(self.threshNew)
self.spinBox.setSingleStep(0.02)
self.spinBox.valueChanged.connect(self.valueChang)
buttonBox = QDialogButtonBox(
QDialogButtonBox.Ok
| QDialogButtonBox.Cancel
| QDialogButtonBox.Apply)
layout = QVBoxLayout()
layout.addWidget(label)
layout.addWidget(self.label2)
layout.addWidget(self.spinBox)
layout.addWidget(buttonBox)
self.resize(300, 200)
self.setLayout(layout)
okBtn = buttonBox.button(QDialogButtonBox.Ok)
okBtn.clicked.connect(self._okBtn)
cancelBtn = buttonBox.button(QDialogButtonBox.Cancel)
cancelBtn.clicked.connect(self.reject)
applyBtn = buttonBox.button(QDialogButtonBox.Apply) # +++
applyBtn.clicked.connect(self._apply) # +++
def _apply(self): # +++
print('Hello Apply')
def _okBtn(self):
print("""
Part : {}
Threshold : {}
ThreshNew : {:,.2f}""".format(
self.part, self.threshold, self.spinBox.value()))
def valueChang(self):
self.label2.setText("ThreshNew : {:,.2f}".format(self.spinBox.value()))
class Window(QWidget):
def __init__(self):
super().__init__()
label = QLabel('Hello Dialog', self)
button = QPushButton('Open Dialog', self)
button.clicked.connect(self.showDialog)
layout = QVBoxLayout()
layout.addWidget(label)
layout.addWidget(button)
self.setLayout(layout)
def showDialog(self):
self.dialog = ModelessDialog(2, 55.77, self)
self.dialog.show()
if __name__ == '__main__':
import sys
app = QApplication(sys.argv)
win = Window()
win.resize(300, 200)
win.show()
sys.exit(app.exec_())
What you are storing in the dlgButtons is just a list of enums, specifically the StandardButton enum, which is a list of identifiers for the buttons, they are not the "actual" buttons.
Also, you cannot use the clicked signal like this:
buttons.clicked(dlgButtons[0])
That will generate a crash, as signals are not callable. The argument of the clicked() signal is what will be received from the slot, which means that if you connect a function to that signal, the function will receive the clicked button:
buttons.clicked.connect(self.buttonsClicked)
def buttonsClicked(self, button):
print(button.text())
The above will print the text of the clicked button (Ok, Apply, Cancel, or their equivalent localized text).
What you're looking for is to connect to the clicked signals of the actual buttons, and you can get the individual reference to each button by using the button() function:
applyButton = buttons.button(qt.QDialogButtonBox.Apply)
applyButton.clicked.connect(self.applyFunction)

Dynamically add and remove a Layout when one of the Radio Button is Selected

I m able to dynamically add a layout to QHBoxLayout in pyqt , however I m unable to remove them once added.
Main aim is to dynamically add and remove a layout based on the Radio Button selected.
def SearchTab(self):
self.layout = QVBoxLayout()
button_layout = QHBoxLayout()
radio_button_1 = QRadioButton("Search")
radio_button_2 = QRadioButton("Update")
button_layout.addWidget(radio_button_1)
button_layout.addWidget(radio_button_2)
self.layout.addItem(button_layout)
radio_button_1.toggled.connect(lambda :self.SelectButtonCheck(radio_button_1))
radio_button_1.toggled.connect(lambda :self.UpdateButtonCheck(radio_button_2))
self.setTabText(0,"Search")
self.tab1.setLayout(self.layout)
def SelectButtonCheck(self,b):
if b.text() == "Search":
if b.isChecked():
print(b.text()+ "is selected")
self.pg_details = pgd.PGDetails()
layout = self.pg_details.returnLayout()
self.layout.addLayout(layout)
def UpdateButtonCheck(self,b):
if b.text() == "Update":
if b.isChecked():
print(b.text()+ " is selected")
for i in range(self.layout.count()):
print(self.layout.itemAt(i))
temp_layout = self.layout.itemAt(i)
widget = temp_layout.widget()
temp_layout.removeItem(temp_layout)
if widget is not None:
widget.deleteLater()
Initial Screen-
Currently I m able to add the layout when "Search" Radio Button is selected --
But Nothing happens when I select "Update" RadioButton
Also find the layouts that have been added-
for i in range(self.layout.count()):
print(self.layout.itemAt(i))
<PyQt5.QtWidgets.QHBoxLayout object at 0x1180ec438>
<PyQt5.QtWidgets.QFormLayout object at 0x1180ff828>
Layouts are being added but not getting removed.
Any leads would be helpful , in what I m missing here
I was able to solve this. Took me a while but understood what is the arrangement of widgets within the layouts.
I assumed removing the layout will cascade delete the widgets itself.
I used the below function to remove the layout and its widgets corresponding to it.
def SearchTab(self):
self.layout = QVBoxLayout()
button_layout = QHBoxLayout()
radio_button_1 = QRadioButton("Search")
radio_button_2 = QRadioButton("Update")
button_layout.addWidget(radio_button_1)
button_layout.addWidget(radio_button_2)
self.layout.addItem(button_layout)
#createDB()
radio_button_1.toggled.connect(lambda :self.SelectButtonCheck(radio_button_1,self.layout))
radio_button_1.toggled.connect(lambda :self.UpdateButtonCheck(radio_button_2,self.layout))
#layout.addRow("Address",QLineEdit())
self.setTabText(0,"Search")
update_layout = QHBoxLayout()
#update_layout.set
#update_btn = QDialogButtonBox(QDialogButtonBox)
#update_btn.setAlignment(Qt.AlignBottom)
update_layout.setAlignment(QtCore.Qt.AlignTop)
update_btn = QPushButton('Update')
reset_btn = QPushButton('Reset')
#self.layout.addRow(update_layout)
update_layout.addWidget(update_btn)
update_layout.addWidget(reset_btn)
update_btn.clicked.connect(self.createDB)
self.tab1.setLayout(self.layout)
def SelectButtonCheck(self,b,stacklayout):
if b.text() == "Search":
if b.isChecked():
print(b.text()+ "is selected")
self.pg_details = pgd.PGDetails()
layout = self.pg_details.returnLayout()
self.layout.addLayout(layout)
def removeLayout(self,layout):
for i in range(layout.count()):
temp_layout = layout.itemAt(i)
if temp_layout is not None:
widget = temp_layout.widget()
if widget is not None:
widget.deleteLater()
else:
return
if temp_layout.layout() is not None:
self.removeLayout(temp_layout.layout())
def removeFormLayout(self,layout):
if layout is not None:
for i in range(layout.count()):
temp_layout = layout.itemAt(i)
if isinstance(temp_layout.layout(),type(QFormLayout())):
self.removeLayout(temp_layout.layout())
else:
next
else:
return
def UpdateButtonCheck(self,b,stacklayout):
if b.text() == "Update":
if b.isChecked():
print(b.text()+ " is selected")
self.removeFormLayout(stacklayout)
The removeFormLayout function picks out the formlayout that I added with the Search radio button and removeLayout removes all the widgets under it as well.
Open to suggestions and improvements in the method used, I tried it with a couple of layout removals other then FormLayout as well. Currently it is working fine.
Also is anybody aware of how to align the HBoxLayout at the top , the radio button starts from the middle again , I want to align them at the top of the screen
Another way is to do the following. QWidget and thus QGroupBox have a show/hide option.
Note, its best to always hide first, otherwise things get wonky
I have a test function that has the following control logic
if isOn:
self.gb1.hide()
self.gb2.show()
else:
self.gb2.hide()
self.gb1.show()
I created a layout that contains both group boxes above. see the sample logic below. I am sure there is a way to do this without storing the variables in the window class.
def create_layout(self):
ly = QHBoxLayout()
self.gb1 = self.create_gb_test1()
self.gb2 = self.create_gb_test2()
ly.addWidget(self.gb1)
ly.addWidget(self.gb2)
return ly
def create_gb_test1(self):
my_name = inspect.currentframe().f_code.co_name
gb = QGroupBox("Find")
btn_find = QPushButton()
ly_horiz = QHBoxLayout()
ly_horiz.addWidget(QLabel("Find:"))
ly_horiz.addWidget(QLineEdit("Some Text", ))
ly_horiz.addWidget(btn_find)
self.ly_find_only = ly_horiz
gb.setLayout(ly_horiz)
return gb
def btn_open_click(self):
pass
def create_gb_test2(self):
my_name = inspect.currentframe().f_code.co_name
gb = QGroupBox("View")
btn_open = QPushButton
cbo = QComboBox()
cbo.addItems(['a', 'b'])
ly_horiz = QHBoxLayout()
ly_horiz.addWidget(QLabel("Find:"))
ly_horiz.addWidget(cbo)
ly_horiz.addWidget(btn_open)
self.ly_find_only = ly_horiz
gb.setLayout(ly_horiz)
return gb

I need help making a menu bar in PyQt5

I have been trying to implement a menu bar in my program for a few days now and i cant seem to get one running. I would like someone to look at my code and give me a template to follow to making a menu bar.
class MainWindow(QMainWindow):
def __init__(self, databaseFilePath, userFilePath):
super(MainWindow,self).__init__()
self.moviesFilePath = moviesFilePath
self.currentUserFilePath = currentUserFilePath
self.createWindow()
def changeFilePath(self):
self.currentUserFilePath = functions_classes.changeFP()
functions_classes.storeFP(self.currentUserFilePath, 1)
def createWindow(self):
self.setWindowTitle('Movies')
#Menu Bar
fileMenuBar = QMenuBar().addMenu('File')
The method changeFilePath is what I would like to be called when a menu option called 'Change user database location' is called from the menu bar File. I have read that actions are the key to this but when every i have tried to implement them they haven't worked.
The QMainWindow class already has a menu-bar.
So you just need to add a menu to it, and then add an action to that menu, like this:
def createUI(self):
...
menu = self.menuBar().addMenu('File')
action = menu.addAction('Change File Path')
action.triggered.connect(self.changeFilePath)
EDIT:
Here's a full, working example based on your example class:
from PyQt5 import QtWidgets
class MainWindow(QtWidgets.QMainWindow):
def __init__(self, databaseFilePath, userFilePath):
super(MainWindow,self).__init__()
self.databaseFilePath = databaseFilePath
self.userFilePath = userFilePath
self.createUI()
def changeFilePath(self):
print('changeFilePath')
# self.userFilePath = functions_classes.changeFilePath()
# functions_classes.storeFilePath(self.userFilePath, 1)
def createUI(self):
self.setWindowTitle('Equipment Manager 0.3')
menu = self.menuBar().addMenu('File')
action = menu.addAction('Change File Path')
action.triggered.connect(self.changeFilePath)
if __name__ == '__main__':
import sys
app = QtWidgets.QApplication(sys.argv)
window = MainWindow('some/path', 'some/other/path')
window.show()
window.setGeometry(500, 300, 300, 300)
sys.exit(app.exec_())
The logic to add a Menubar with usable items is something like this
def createUI(self):
self.setWindowTitle('Equipment Manager 0.3')
#Menu Bar
fileMenuBar = QMenuBar(self)
menuFile = QMenu(fileMenuBar)
actionChangePath = QAction(tr("Change Path"), self)
fileMenuBar.addMenu(menuFile)
menuFile.addAction(actionChangePath)
Then you just need to connect the action actionChangePath to the signal triggered() with something like
connect(actionChangePath,SIGNAL("triggered()"), changeFilePath)
Probably there are some better solution (but why did you not use the Designer ?), but this one should be work

Removing thin borders between widgets in Qt

In particular I have 2 questions:
1) How can I remove those thin lines between the widgets? setMargin(0) and setSpacing(0)
are already set.
2) In a further step I want to remove the window title bar with FramelessWindowHint.
To drag the window, I'll bind a mouseevent on the upper dark yellow widget. Right now, the upper widget is a QTextEdit with suppressed keyboard interactions. For the draging purpose, I doubt this widget is good... So the question is, what other widgets are good to create a colored handle to drag the window? Perhaps QLabel?
EDIT: Here is the code. I only used QTestEdit-Widgets.
from PyQt4.QtGui import *
from PyQt4 import QtGui,QtCore
import sys
class Note(QWidget):
def __init__(self, parent = None):
super(QWidget, self).__init__(parent)
self.createLayout()
self.setWindowTitle("Note")
def createLayout(self):
textedit = QTextEdit()
grip = QTextEdit()
grip.setMaximumHeight(16) #reduces the upper text widget to a height to look like a grip of a note
grip.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff) #suppresses the scroll bar that appears under a certain height
empty = QTextEdit()
empty.setMaximumHeight(16)
empty.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
resize = QTextEdit()
resize.setMaximumHeight(16)
resize.setMaximumWidth(16)
resize.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
layout = QVBoxLayout()
layout.addWidget(grip)
layout.addWidget(textedit)
layout.setMargin(0)
layout.setSpacing(0)
layoutBottom=QHBoxLayout()
layoutBottom.addWidget(empty)
layoutBottom.addWidget(resize)
layout.addLayout(layoutBottom)
self.setLayout(layout)
# Set Font
textedit.setFont(QFont("Arial",16))
# Set Color
pal=QtGui.QPalette()
rgb=QtGui.QColor(232,223,80) #Textwidget BG = yellow
pal.setColor(QtGui.QPalette.Base,rgb)
textc=QtGui.QColor(0,0,0)
pal.setColor(QtGui.QPalette.Text,textc)
textedit.setPalette(pal)
empty.setPalette(pal)
pal_grip=QtGui.QPalette()
rgb_grip = QtGui.QColor(217,207,45)
pal_grip.setColor(QtGui.QPalette.Base,rgb_grip)
textc_grip=QtGui.QColor(0,0,0)
pal.setColor(QtGui.QPalette.Text,textc_grip)
grip.setPalette(pal_grip)
resize.setPalette(pal_grip)
resize.setTextInteractionFlags(QtCore.Qt.NoTextInteraction)
empty.setTextInteractionFlags(QtCore.Qt.NoTextInteraction)
grip.setTextInteractionFlags(QtCore.Qt.NoTextInteraction)
#textedit.setTextInteractionFlags(QtCore.Qt.NoTextInteraction) #total text widget lock
#textedit.setTextInteractionFlags(QtCore.Qt.TextSelectableByMouse) #Lock?
#http://qt-project.org/doc/qt-4.8/qt.html#TextInteractionFlag-enum
#self.setWindowFlags(QtCore.Qt.FramelessWindowHint) #removes the title bar
#self.setWindowFlags(QtCore.Qt.WindowStaysOnTopHint) #to make the window stay on top
class Main():
def __init__(self):
self.notes=[]
self.app = QApplication(sys.argv)
self.app.setQuitOnLastWindowClosed(False);
self.trayIcon = QSystemTrayIcon(QIcon(r"C:\Users\Thomas\Desktop\SimpleNotes.ico"), self.app)
self.menu = QMenu()
self.newWindow = self.menu.addAction("New note")
self.separator = self.menu.addSeparator()
self.hideNotes = self.menu.addAction("Hide all notes")
self.showNotes = self.menu.addAction("Show all notes")
self.separator = self.menu.addSeparator()
self.saveNotes = self.menu.addAction("Save notes")
self.loadNotes = self.menu.addAction("Load notes")
self.separator = self.menu.addSeparator()
self.showHelp = self.menu.addAction("Show help")
self.showAbout = self.menu.addAction("Show about")
self.separator = self.menu.addSeparator()
self.exitAction = self.menu.addAction("Quit notes")
self.exitAction.triggered.connect(self.close)
self.newWindow.triggered.connect(self.newNote)
self.trayIcon.setContextMenu(self.menu)
self.trayIcon.show()
self.app.exec()
def newNote(self):
print("Create new note entry has been clicked")
note=Note()
note.show()
self.notes.append(note)
print(self.notes)
def hideNotes(self):
pass
def showNotes(self):
pass
def saveNotes(self):
pass
def loadNotes(self):
pass
def showHelp(self):
pass
def showAbout(self):
pass
def close(self):
self.trayIcon.hide()
self.app.exit()
print("Exit menu entry has been clicked")
if __name__ == '__main__':
Main()
The answer from thuga was good enough, so i post it here:
textedit.setFrameShape(QtGui.QFrame.NoFrame)
and
grip.setFrameShape(QtGui.QFrame.NoFrame)
made the line disappear.
for 1. I've used:
textEdit.setFrameStyle(QtGui.QFrame.NoFrame)
ui->fr200->setFrameShape(QFrame::NoFrame);
ui->fr201->setFrameShape(QFrame::NoFrame);
ui->fr202->setFrameShape(QFrame::NoFrame);
ui->fr203->setFrameShape(QFrame::NoFrame);
ui->fr204->setFrameShape(QFrame::NoFrame);
ui->fr205->setFrameShape(QFrame::NoFrame);
ui->fr206->setFrameShape(QFrame::NoFrame);
ui->fr207->setFrameShape(QFrame::NoFrame);
ui->fr208->setFrameShape(QFrame::NoFrame);

Categories