PyQt5 refreshing layout or widget - pyqt5

buttons are generated from sql database. When you run only one application, the widget refreshes itself. By clicking successive buttons, the text in the groupbox changes correctly, while the vbox in the groupbox is only pressed. Code below.
def GuiClient(self):
self.vbox_klient = QVBoxLayout()
klienci_button = QHBoxLayout()
buttons_klienci_layout = QGridLayout()
baza = sql.DB()
klienci = baza.listNameClients()
buttons ={}
for b in range(len(self.lista_klient)):
buttons[self.lista_klient[b]] = (0, lista_pos[b])
self.group_button_klienci = QButtonGroup()
self.group_button_klienci.buttonClicked[int].connect(self.one_button_click_clients)
for btn_txt, pos in buttons.items():
buttons[btn_txt] = QPushButton(btn_txt)
buttons[btn_txt].setFixedSize(120, 35)
buttons_klienci_layout.addWidget(buttons[btn_txt], pos[0], pos[1])
buttons[btn_txt].setCheckable(True)
self.group_button_klienci.addButton(buttons[btn_txt], pos[1])
klienci_button.addLayout(buttons_klienci_layout)
self.vbox_klient.addLayout(klienci_button)
self.klient_body = QVBoxLayout()
self.group_klient_null = QGroupBox('Clients')
self.klient_body.addWidget(self.group_klient_null)
self.group_klient_select = QGroupBox(self)
self.group_klient_select.setVisible(False)
self.klient_body.addWidget(self.group_klient_select)
self.vbox_klient.addLayout(self.klient_body)
def one_button_click_clients(self, num_kl):
if num_kl < 0:
self.group_klient_null.setVisible(True)
self.group_klient_select.setVisible(False)
if num_kl >=0:
temp = num_kl+1
indeks_client = num_kl +1
self.group_klient_select.setTitle(self.lista_klient[num_kl])
self.group_klient_null.setVisible(False)
self.group_klient_select.setVisible(True)
vbox = QVBoxLayout()
buton =QPushButton()
buton.setText('OK' + self.lista_klient[num_kl])
vbox.addWidget(buton)
print(self.lista_klient[num_kl])
self.group_klient_select.setLayout(vbox)

Related

Reducing vertical space between radio buttons in PyQT

I'm trying to condense the vertical spacing between a group of radio buttons in PyQT and am struggling. I would like the 3 options in the picture to be vertically closer together...
Code for reproducing:
class MyPopUp(QWidget):
def __init__(self, task=None):
super(MyPopUp, self).__init__()
self.task = task
self.setMinimumSize(400,600)
self.populate_fields()
def populate_fields(self):
self.task_popup_layout = QVBoxLayout()
self.setLayout(self.task_popup_layout)
# When do you need to get it done by
self.scheduling_header_label = QLabel("<h3>Getting it done</h3>")
self.task_popup_layout.addWidget(self.scheduling_header_label)
# Deadline date
self.deadline_layout = QHBoxLayout()
self.deadline_date_label = QLabel("When does it need to be complete by?")
self.deadline_layout.addWidget(self.deadline_date_label)
self.deadline_dateedit = QDateEdit(calendarPopup=True)
self.deadline_dateedit.setAlignment(Qt.AlignmentFlag.AlignRight)
self.deadline_dateedit.setDateTime(datetime.now() + timedelta(days=7))
self.deadline_layout.addWidget(self.deadline_dateedit)
self.task_popup_layout.addLayout(self.deadline_layout)
# Type of deadline
self.deadline_type_layout = QHBoxLayout()
self.task_popup_layout.addLayout(self.deadline_type_layout)
self.deadline_type_label = QLabel("How strict is the deadline")
self.deadline_type_label.setWordWrap(True)
self.deadline_type_layout.addWidget(self.deadline_type_label)
self.deadline_group_layout = QVBoxLayout()
self.deadline_type_layout.addLayout(self.deadline_group_layout)
self.deadline_group = QButtonGroup()
self.soft_deadline_radio = QRadioButton("Target Deadline")
self.deadline_group_layout.addWidget(self.soft_deadline_radio)
self.deadline_group.addButton(self.soft_deadline_radio)
self.hard_deadline_radio = QRadioButton("Hard Deadline")
self.hard_deadline_radio.setChecked(True)
self.deadline_group_layout.addWidget(self.hard_deadline_radio)
self.deadline_group.addButton(self.hard_deadline_radio)
self.specific_deadline_radio = QRadioButton("Must be done on this exact day")
self.deadline_group_layout.addWidget(self.specific_deadline_radio)
self.deadline_group.addButton(self.specific_deadline_radio)

How to open context menu for an object that is empty, but has a size?

I am creating a GUI for a dependency graphing software... And am not able to figure out how to get a context menu to open for my lines.
What I want to do, right click on/near a MyLine widget and open a context menu... What is happening right clicks are not detected.
It is currently not detecting right clicks on the line widgets location to open a context menu (Purpose of this is to allow the user to delete/edit lines by right clicking on them).
What am I doing wrong here?
class MyLine(QWidget):
def __init__(self, destination: Node, source: Node, parent=None):
super().__init__(parent)
self.setContextMenuPolicy(Qt.CustomContextMenu)
self.customContextMenuRequested.connect(self.showMenu)
self.destination = destination
self.source = source
self.setAutoFillBackground(True)
p = self.palette()
p.setColor(self.backgroundRole(), Qt.red)
self.setPalette(p)
def update_line_size(self):
origin = self.source.get_line_draw_pos(self.destination.pos())
destination = self.destination.get_line_draw_pos(self.source.pos())
leftcornerX = origin.x() if origin.x() < destination.x() else destination.x()
leftcornerY = origin.y() if origin.y() < destination.y() else destination.y()
sizeX = abs(origin.x() - destination.x())
sizeY = abs(origin.y() - destination.y())
self.setGeometry(leftcornerX, leftcornerY, sizeX, sizeY)
def showMenu(self, _):
menu = QMenu()
menu.addAction("Delete", self.remove)
menu.exec_(self.cursor().pos())
def draw(self, painter: QPainter):
origin = self.source.get_line_draw_pos(self.destination.pos())
destination = self.destination.get_line_draw_pos(self.source.pos())
painter.drawLine(origin, destination)
# DRAW ARROW HEAD
ARROW_SIZE = 10 # Might change
line_angle = calculate_line_angle(destination, origin)
draw_arrow_head(destination, painter, line_angle, ARROW_SIZE)
def remove(self):
self.parent().delete_line(self)
self.deleteLater()
Edit:
required types for reproducibility
class Node(QLabel):
def __init__(self, text: str, parent=None):
super().__init__(text, parent)
self.setContextMenuPolicy(Qt.CustomContextMenu)
self.customContextMenuRequested.connect(self.showMenu)
def get_line_draw_pos(self, other_side: QPoint):
x = self.pos().x() if other_side.x() < self.pos().x() else (self.pos().x() + self.width())
y = self.pos().y() if other_side.y() < self.pos().y() else (self.pos().y() + self.height())
return QPoint(x, y)
def showMenu(self, _):
pass #purposefully left as a stub
def calculate_line_angle(destination: QPoint, origin: QPoint):
return math.atan2(destination.y() - origin.y(), destination.x() - origin.x())
def draw_arrow_head(destination: QPoint, painter: QPainter, line_angle: float, arrow_size: float = 10):
angle1 = math.radians(22.5) + line_angle
angle2 = math.radians(-22.5) + line_angle
arrow1 = QPoint( int(destination.x() - arrow_size * math.cos(angle1)), int(destination.y() - arrow_size * math.sin(angle1)))
arrow2 = QPoint( int(destination.x() - arrow_size * math.cos(angle2)), int(destination.y() - arrow_size * math.sin(angle2)))
painter.drawLine(destination, arrow1)
painter.drawLine(destination, arrow2)
class MainWindow(QWidget):
def __init__(self):
super().__init__()
self.setAcceptDrops(True) # add a drop rule
self.setMouseTracking(True)
self.track_origin = None
self.track_mouse = QPoint(0,0)
self.lines = []
def paintEvent(self, event):
painter = QPainter(self)
for line in self.lines:
line.draw(painter)
line.update_line_size()
def connectNodes(self, destination: Node, source: Node):
self.lines.append(MyLine(destination, source))
self.update()
def delete_line(self, line: MyLine):
self.lines.remove(line)
self.update()
app = QApplication([])
window = MainWindow()
window.setWindowTitle("Right Click to remove label")
window.setGeometry(100, 100, 400, 200)
window.move(60,15)
nodes = []
for index, node_name in enumerate(["hello.txt", "not_a_villain.txt", "nope.txt"]):
node = Node(node_name, window)
node.move(50 + index*100, 50 + (index%2) * 50)
nodes.append(node)
window.connectNodes(nodes[0], nodes[1])
window.connectNodes(nodes[0], nodes[2])
window.connectNodes(nodes[1], nodes[2])
window.show()
sys.exit(app.exec_())

Setting the focuspolicy of differents class of widgets

I am currently learning PyQt concepts. Through easy examples, I am trying to play with the tab key to jump from one widget to another.
I manage to disable the focus policy on a PushButton, making it impossible to get the focus on it while pushing Tab. However, with a DialogButton, I do not manage to do so.
I feel managing this policy is possible with every type of widget, but I feel a bit lost with all their specificities.
Here is my current code :
from PyQt5 import QtWidgets, QtCore, QtGui
import sys
class TabWidget(QtWidgets.QDialog): # class to implement dialog box
def __init__(self):
super().__init__()
self.setWindowTitle("Tab Widget App")
tabWidget = QtWidgets.QTabWidget() # creation of the tab widget object
tabWidget.addTab(FirstTab(), "First Tab") # fill with first widget
tabWidget.addTab(SecondTab(), "Second Tab")
tabWidget.addTab(ThirdTab(), "Third Tab")
self.buttonbox = QtWidgets.QDialogButtonBox(QtWidgets.QDialogButtonBox.Ok | QtWidgets.QDialogButtonBox.Cancel)
self.buttonbox.setFocusPolicy(QtCore.Qt.NoFocus)
self.buttonbox.accepted.connect(self.accept)
self.buttonbox.rejected.connect(self.reject)
tabWidget.addTab(FourthTab(), "Fourth Tab")
vbox_layout = QtWidgets.QVBoxLayout()
vbox_layout.addWidget(tabWidget)
vbox_layout.addWidget(self.buttonbox)
self.setLayout(vbox_layout)
def keyPressEvent(self, event):
print(event.key())
class FirstTab(QtWidgets.QWidget): # class to implement simple widget
def __init__(self):
super().__init__()
name = QtWidgets.QLabel("Name:")
nameEdit = QtWidgets.QLineEdit()
dob = QtWidgets.QLabel("Birth Date:")
dobEdit = QtWidgets.QLineEdit()
age = QtWidgets.QLabel("Age:")
ageEdit = QtWidgets.QLineEdit()
phone = QtWidgets.QLabel("Phone:")
phoneEdit = QtWidgets.QLineEdit()
vbox_layout = QtWidgets.QVBoxLayout()
vbox_layout.addWidget(name)
vbox_layout.addWidget(nameEdit)
vbox_layout.addWidget(dob)
vbox_layout.addWidget(dobEdit)
vbox_layout.addWidget(age)
vbox_layout.addWidget(ageEdit)
vbox_layout.addWidget(phone)
vbox_layout.addWidget(phoneEdit)
self.setLayout(vbox_layout)
class SecondTab(QtWidgets.QWidget): # class to implement simple widget
def __init__(self):
super().__init__()
selectGroup = QtWidgets.QGroupBox("Select Operating Systems")
combo = QtWidgets.QComboBox()
list = {"Windows", "Mac", "Linux"}
combo.addItems(list)
selectLayout = QtWidgets.QVBoxLayout()
selectLayout.addWidget(combo)
selectGroup.setLayout(selectLayout)
checkGroup = QtWidgets.QGroupBox("Which Operation System Do You Like?")
windows = QtWidgets.QCheckBox("Windows")
mac = QtWidgets.QCheckBox("Mac")
linux = QtWidgets.QCheckBox("Linux")
checklayout = QtWidgets.QVBoxLayout()
checklayout.addWidget(windows)
checklayout.addWidget(mac)
checklayout.addWidget(linux)
checkGroup.setLayout(checklayout)
mainlayout = QtWidgets.QVBoxLayout()
mainlayout.addWidget(selectGroup)
mainlayout.addWidget(checkGroup)
self.setLayout(mainlayout)
class ThirdTab(QtWidgets.QWidget):
def __init__(self):
super().__init__()
label = QtWidgets.QLabel("Terms And Conditions")
listwidget = QtWidgets.QListWidget()
list = []
for i in range(1,20):
list.append("This Is Terms And Conditions")
listwidget.insertItems(0, list)
checkbox = QtWidgets.QCheckBox("Agree The Terms And Condition")
layout = QtWidgets.QVBoxLayout()
layout.addWidget(label)
layout.addWidget(listwidget)
layout.addWidget(checkbox)
self.setLayout(layout)
class FourthTab(QtWidgets.QWidget):
def __init__(self):
super().__init__()
self.groupBox = QtWidgets.QGroupBox("Issue", objectName = 'groupBox')
self.grid_layout = QtWidgets.QGridLayout(self.groupBox)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Minimum)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
self.widgetOne = QtWidgets.QTextEdit(self.groupBox, tabChangesFocus = True)
self.widgetOne_label = QtWidgets.QLabel("widgetOne")
self.widgetOne.setObjectName("WidgetOne")
self.grid_layout.addWidget(self.widgetOne, 1, 0, 1, 1)
self.grid_layout.addWidget(self.widgetOne_label, 0, 0, 1, 1)
sizePolicy.setHeightForWidth(self.widgetOne.sizePolicy().hasHeightForWidth())
self.grid_layout.addWidget
self.widgetTwo = QtWidgets.QTextEdit(self.groupBox, tabChangesFocus = True)
self.widgetTwo_label = QtWidgets.QLabel("widgetTwo")
self.widgetTwo.setObjectName("widgetTwo")
self.grid_layout.addWidget(self.widgetTwo, 1, 1, 1, 1)
self.grid_layout.addWidget(self.widgetTwo_label, 0, 1, 1, 1)
sizePolicy.setHeightForWidth(self.widgetTwo.sizePolicy().hasHeightForWidth())
self.grid_layout.addWidget
self.widgetThree = QtWidgets.QTextEdit(self.groupBox, tabChangesFocus = True)
self.widgetThree_label = QtWidgets.QLabel("widgetThree")
self.widgetThree.setObjectName("widgetThree")
self.grid_layout.addWidget(self.widgetThree, 4, 0, 1, 1)
self.grid_layout.addWidget(self.widgetThree_label, 3, 0, 1, 1)
sizePolicy.setHeightForWidth(self.widgetThree.sizePolicy().hasHeightForWidth())
self.grid_layout.addWidget
self.widgetFour = QtWidgets.QTextEdit(self.groupBox, tabChangesFocus = True)
self.widgetFour_label = QtWidgets.QLabel("widgetFour")
self.widgetFour.setObjectName("WidgetFour")
self.grid_layout.addWidget(self.widgetFour, 4, 1, 1, 1)
self.grid_layout.addWidget(self.widgetFour_label, 3, 1, 1, 1)
sizePolicy.setHeightForWidth(self.widgetFour.sizePolicy().hasHeightForWidth())
self.grid_layout.addWidget
v_layout = QtWidgets.QVBoxLayout()
v_layout.addWidget(self.groupBox)
self.setLayout(v_layout)
self.setTabOrder(self.widgetOne, self.widgetTwo)
self.setTabOrder(self.widgetTwo, self.widgetThree)
self.setTabOrder(self.widgetThree, self.widgetFour)
self.setTabOrder(self.widgetFour, self.widgetOne)
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
tabwidget = TabWidget()
tabwidget.show()
sys.exit(app.exec_())
The involved button is my "buttonbox" of type QDialogButton. I have set the focus policy to NoFocus. But when I launch the script and use the tab key in FourthTab, the focus still goes on OK / Cancel.
Are there some restrictions about this option? Or is there something I am missing?
The focus policy is not propagated to the children.
When you set the focus policy on the button box, its children (the buttons) still have their default policy (which is StrongFocus).
If you want to disable that for all buttons, you need to do it explicitly, for instance:
self.buttonbox.button(self.buttonbox.Ok).setFocusPolicy(QtCore.Qt.NoFocus)
Or, for any button:
for button in self.buttonbox.findChildren(QtWidgets.QAbstractButton):
button.setFocusPolicy(QtCore.Qt.NoFocus)
Note that the keyPressEvent is only received by a parent if none of its children has handled it, so if you're trying to capture the Tab you need to install an event filter on the whole QApplication instead, otherwise it's still possible that some widget will capture and accept it, thus preventing you to receive it.

Pyqt5 synchronization between two tabwidget which are in different window

I want to make new window by double click tabwidget.
and copy tabwidget's (child which is tablewidget) to new window.
and finally, changing item of new window's tablewidget needs to change mainwindow's tablewidget.
would it be possible?
I have seen this, that answer does copy tabwidget to new window
but remove mainwindow tabwidget.
here is I worked so far.
I managed to make new dialog by double click, but other things.. I dont' have any clues. can anyone can help?
#!/usr/bin/python
# -*- coding: utf8 -*-
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
import sys
class DetachableTabWidget(QTabWidget):
def __init__(self, parent=None):
QTabWidget.__init__(self)
self.tabBar = self.TabBar(self)
self.tabBar.onDetachTabSignal.connect(self.detachTab)
self.setTabBar(self.tabBar)
print("DetachableTabWidget")
#pyqtSlot(int, QPoint)
def detachTab(self, index, point):
print("detachTab")
all_list = []
list1 = []
list2 = []
name = self.tabText(index)
icon = self.tabIcon(index)
if icon.isNull():
icon = self.window().windowIcon()
contentWidget = self.widget(index)
contentWidgetRect = contentWidget.frameGeometry()
tablewidgetA = contentWidget.findChild(QTableWidget)
for i in range(tablewidgetA.rowCount()):
list1.append(tablewidgetA.item(i, 0).text())
list2.append(tablewidgetA.item(i, 1).text())
all_list.append(list1)
all_list.append(list2)
detachedTab = self.DetachedTab(all_list)
detachedTab.setWindowModality(Qt.NonModal)
detachedTab.setWindowTitle(name)
detachedTab.setWindowIcon(icon)
detachedTab.setObjectName(name)
detachedTab.setGeometry(contentWidgetRect)
detachedTab.move(point)
detachedTab.exec_()
class DetachedTab(QDialog) :
onCloseSignal = pyqtSignal(QWidget,type(''), QIcon)
# def __init__(self, contentWidget, parent=None):
def __init__(self, all_list, parent=None) :
print("DetachedTab")
super().__init__()
layout = QVBoxLayout(self)
table = QTableWidget()
table.setColumnCount(len(all_list))
table.setRowCount(len(all_list[0]))
for col in range(len(all_list)) :
for row in range(len(all_list[col])) :
item = QTableWidgetItem(all_list[col][row])
table.setItem(row, col, item)
layout.addWidget(table)
table.show()
class TabBar(QTabBar):
onDetachTabSignal = pyqtSignal(int, QPoint)
onMoveTabSignal = pyqtSignal(int, int)
def __init__(self, parent=None):
QTabBar.__init__(self, parent)
self.setAcceptDrops(True)
self.setElideMode(Qt.ElideRight)
self.setSelectionBehaviorOnRemove(QTabBar.SelectLeftTab)
self.dragStartPos = QPoint()
self.dragDropedPos = QPoint()
self.mouseCursor = QCursor()
self.dragInitiated = False
def mouseDoubleClickEvent(self, event) :
event.accept()
self.onDetachTabSignal.emit(self.tabAt(event.pos()), self.mouseCursor.pos())
class SurfViewer(QMainWindow):
def __init__(self, parent=None):
super(SurfViewer, self).__init__()
self.parent = parent
self.centralTabs = DetachableTabWidget()
self.setCentralWidget(self.centralTabs)
self.setFixedWidth(600)
self.setFixedHeight(600)
#tab 1
self.tab_1 = QWidget()
self.centralTabs.addTab(self.tab_1,"Tab 1")
vbox = QVBoxLayout()
Table = QTableWidget(2, 2)
vbox.addWidget(Table)
item = QTableWidgetItem("table 1 content")
Table.setItem( 0, 0, item)
item = QTableWidgetItem("table 2 content")
Table.setItem( 0, 1, item)
item = QTableWidgetItem("table 3 content")
Table.setItem( 1, 0, item)
item = QTableWidgetItem("table 4 content")
Table.setItem( 1, 1, item)
vbox.setAlignment(Qt.AlignTop)
self.tab_1.setLayout(vbox)
#tab 2
self.tab_2 = QWidget()
self.centralTabs.addTab(self.tab_2,"Tab 2")
vbox = QVBoxLayout()
Table = QTableWidget(2, 2)
item = QTableWidgetItem("table 2 content")
Table.setItem( 0, 0, item)
item = QTableWidgetItem("table 3 content")
Table.setItem( 0, 1, item)
item = QTableWidgetItem("table 4 content")
Table.setItem( 1, 0, item)
item = QTableWidgetItem("table 5 content")
Table.setItem( 1, 1, item)
vbox.addWidget(Table)
vbox.setAlignment(Qt.AlignTop)
self.tab_2.setLayout(vbox)
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = SurfViewer(app)
ex.setWindowTitle('window')
ex.show()
sys.exit(app.exec_( ))
If you want to synchronize data between item views, you have to use a common model. Since you're using a QTableWidget (which has an internal, private model, and a higher level item view) you can create a new window using a QTableView instead, and set its model to the source. In that case, you don't need to "copy" row/column/data, you only need to use the source model.
Here's a modified version of your script:
class DetachableTabWidget(QTabWidget):
# ...
#pyqtSlot(int, QPoint)
def detachTab(self, index, point):
print("detachTab")
name = self.tabText(index)
icon = self.tabIcon(index)
if icon.isNull():
icon = self.window().windowIcon()
contentWidget = self.widget(index)
contentWidgetRect = contentWidget.frameGeometry()
tablewidgetA = contentWidget.findChild(QTableWidget)
detachedTab = self.DetachedTab(tablewidgetA.model())
detachedTab.setWindowTitle(name)
detachedTab.setWindowIcon(icon)
detachedTab.setObjectName(name)
detachedTab.setGeometry(contentWidgetRect)
detachedTab.move(point)
detachedTab.exec_()
class DetachedTab(QDialog) :
onCloseSignal = pyqtSignal(QWidget,type(''), QIcon)
def __init__(self, model, parent=None) :
print("DetachedTab")
super().__init__()
layout = QVBoxLayout(self)
table = QTableView()
table.setModel(model)
layout.addWidget(table)
table.show()
With this code you can modify the "child" window table data, and it will always synchronize the source table widget.

ScrolledPanel not resizing after DestroyChildren

I got this code from a topic on Stackoverflow ScrolledPanel inside Panel not sizing. It works well for me. However I want to destroy all children of the scrolled_panel then recreate its new children. So I modify the code like this:
import wx
import wx.lib.scrolledpanel as scrolled
########################################################################
class MyForm(wx.Frame):
#----------------------------------------------------------------------
def __init__(self):
wx.Frame.__init__(self, None, wx.ID_ANY, "Tutorial", size=(200,500))
self.n = 13
# Add a panel so it looks the correct on all platforms
self.panel = wx.Panel(self, wx.ID_ANY)
# --------------------
# Scrolled panel stuff
self.scrolled_panel = scrolled.ScrolledPanel(self.panel, -1,
style = wx.TAB_TRAVERSAL|wx.SUNKEN_BORDER, name="panel1")
self.scrolled_panel.SetAutoLayout(1)
self.scrolled_panel.SetupScrolling()
words = "A Quick Brown Insane Fox Jumped Over the Fence and Ziplined to Cover".split()
self.spSizer = wx.BoxSizer(wx.VERTICAL)
for word in words:
text = wx.TextCtrl(self.scrolled_panel, value=word)
self.spSizer.Add(text)
self.scrolled_panel.SetSizer(self.spSizer)
# --------------------
btn = wx.Button(self.panel, label="Add Widget")
btn.Bind(wx.EVT_BUTTON, self.onAdd)
panelSizer = wx.BoxSizer(wx.VERTICAL)
panelSizer.AddSpacer(50)
panelSizer.Add(self.scrolled_panel, 1, wx.EXPAND)
panelSizer.Add(btn)
self.panel.SetSizer(panelSizer)
#----------------------------------------------------------------------
def onAdd(self, event):
""""""
print "in onAdd"
self.n += 1
self.scrolled_panel.DestroyChildren()
for i in range(self.n):
new_text = wx.TextCtrl(self.scrolled_panel, value="New Text %s" % i)
self.spSizer.Add(new_text)
#new_text = wx.TextCtrl(self.scrolled_panel, value="New Text")
#self.spSizer.Add(new_text)
self.scrolled_panel.Layout()
self.scrolled_panel.SetupScrolling()
# Run the program
if __name__ == "__main__":
app = wx.App(False)
frame = MyForm().Show()
app.MainLoop()
Now, even when I create the children more than the panel's size can show, I don't see the scroll bar as the original code. Can any one help me with this? Thanks ahead!!!
I solved this problem by adding testpanel to add scrolledPanel in it. Whennever onAdd() is call, after destroying all of testpanel's children, everything under the testpanel even the sizer have to be re-created and re-setup.
I've tried to do like that without the testpanel, I still could scroll by using my mouse, but didn't see the scrollbar, I don't know why. This is my new code:
import wx
import wx.lib.scrolledpanel as scrolled
########################################################################
class MyForm(wx.Frame):
#----------------------------------------------------------------------
def __init__(self):
wx.Frame.__init__(self, None, wx.ID_ANY, "Tutorial", size=(200,500))
self.n =17
# Add a panel so it looks the correct on all platforms
self.panel = wx.Panel(self, wx.ID_ANY)
panelSizer = wx.BoxSizer(wx.VERTICAL)
panelSizer.AddSpacer(50)
# add a panel
self.testpanel = wx.Panel(self.panel, wx.ID_ANY)
#self.testpanel.SetSizer(self.testpanelSizer)
panelSizer.Add(self.testpanel, 1, wx.EXPAND)
self.onAdd()
btn = wx.Button(self.panel, label="Add Widget")
btn.Bind(wx.EVT_BUTTON, self.onAdd)
panelSizer.Add(btn)
self.panel.SetSizer(panelSizer)
#----------------------------------------------------------------------
def onAdd(self, event=None):
self.n +=1
self.testpanel.DestroyChildren()
testpanelSizer = wx.BoxSizer(wx.VERTICAL)
scrolled_panel = scrolled.ScrolledPanel(self.testpanel, -1,
style = wx.TAB_TRAVERSAL|wx.SUNKEN_BORDER, name="panel1")
scrolled_panel.SetAutoLayout(1)
scrolled_panel.SetupScrolling()
spSizer = wx.BoxSizer(wx.VERTICAL)
for i in range(self.n):
new_text = wx.TextCtrl(scrolled_panel, value="New Text %s" % i)
spSizer.Add(new_text)
scrolled_panel.SetSizer(spSizer)
testpanelSizer.Add(scrolled_panel, 1, wx.EXPAND)
self.testpanel.SetSizer(testpanelSizer)
self.testpanel.Layout()
# Run the program
if __name__ == "__main__":
app = wx.App(False)
frame = MyForm().Show()
app.MainLoop()