I have Gtk.Grid and after resizing window, it does not refresh (event columns and everything is set up correctly), but when you resize it again or click on item, it will redraw.
Gtk.main_iteration() causes segfault in python3
from gi.repository import GLib, Gtk
class Grid(Gtk.Grid):
min_width = 400
min_height = 300
min_spacing = 20
def __init__(self):
Gtk.Grid.__init__(self, name='feed_grid',
row_spacing=20, column_spacing=20)
self.set_column_homogeneous(True)
self.set_size_request(self.min_width, self.min_height)
self.connect('size-allocate', self._on_size_allocate)
self._cols = 2
def _on_size_allocate(self, widget, allocation):
self.set_width(allocation.width)
def set_width(self, width):
self._cols = (width + self.min_spacing) // self.min_width
self._rebuild_grid()
def get_columns(self):
return self._cols
def add_feed(self, feed):
feed.set_order(len(self.get_children()))
self._attach_feed(feed)
feed.show_all()
def _rebuild_grid(self):
for feed in self.get_children():
self.remove(feed)
self._attach_feed(feed)
def _attach_feed(self, feed):
y, x = divmod(feed.get_order(), self.get_columns())
self.attach(feed, x, y, 1, 1)
Bug report
https://bugs.launchpad.net/ubuntu/+source/gtk+3.0/+bug/987565
Video
https://launchpadlibrarian.net/102937139/floaty%20resize.ogv
Related
I'm using VS code with metal scala extension and cannot get my code to format properly. I want to have 8 spaces tab width for everything. This is my .scalafmt.conf
version = "2.0.0-RC4"
maxColumn = 80
continuationIndent.callSite = 8
continuationIndent.defnSite = 8
Then I press Ctrl+Shift+I to format the document. Only the call sites are aligned with 8 spaces, the definition sites are aligned to 2 spaces only.
This is what my formatted code looks like.
final class Goods(
_food: Int = 0,
_materials: Int = 0,
_products: Int = 0,
_fuel: Int = 0
) {
var raw = Array(_food, _materials, _products, _fuel)
def food: Int = raw(0)
def materials: Int = raw(1)
def products: Int = raw(2)
def fuel: Int = raw(3)
def weight = raw.sum
}
Why isn't the body of the class aligned with 8 space?
Because the developers of scalafmt arbitrarily don't want you to have control over your own tab width. This is the main reason I'm using scalariform instead.
https://github.com/scalameta/scalafmt/issues/1493
In the code below, DrawRect1 and DrawRect2 represent a simplified version of functions that draw multiple shapes on screen.
I want to display some supplementary information if I hover over any of the drawn rectangles (similar to the way a tooltip works). But I need to generate that display information from a function rather than static definition.
Given I know the coords of the draw rectangle, can I either create another type of object with the same coords, or link a hover action to each drawnrectangle, so that I could call a function defined something like this ? :
EDIT: I guess I need a object I can bind a wx.EVT_ENTER_WINDOW event to, that I can create at the same time as dc.DrawRectangle ? Or can I bind this handler to the panel and use x,y position to try and match to a list of drawn rectangle coords ?
The closest thing I could find on SO was this old question, wxpython tooltip at specific coordinates but it wasn't a comprehensive answer.
import wx
class Mywin(wx.Frame):
def __init__(self, parent, title):
super(Mywin, self).__init__(parent, title=title, size=(500, 300))
self.InitUI()
def InitUI(self):
self.panel = wx.Panel(self)
self.panel.SetBackgroundColour(wx.Colour('RED'))
self.Centre()
self.Show(True)
menuBar = wx.MenuBar()
RectangleButton = wx.Menu()
Item1 = RectangleButton.Append(wx.ID_ANY, 'Rectangle 1')
Item2 = RectangleButton.Append(wx.ID_ANY, 'Rectangle 2')
menuBar.Append(RectangleButton, 'Rectangles')
self.SetMenuBar(menuBar)
self.Bind(wx.EVT_MENU, self.DrawRect1, Item1)
self.Bind(wx.EVT_MENU, self.DrawRect2, Item2)
def DrawRect1(self, e):
self.panel.SetBackgroundColour(wx.Colour('BLUE'))
self.Refresh()
self.Update()
self.dc = wx.ClientDC(self.panel)
self.dc.SetBrush(wx.Brush(wx.Colour('white')))
self.dc.DrawRectangle(10, 10, 100, 100)
def DrawRect2(self, e):
self.panel.SetBackgroundColour(wx.Colour('GREEN'))
self.Refresh()
self.Update()
self.dc = wx.ClientDC(self.panel)
self.dc.SetBrush(wx.Brush(wx.Colour('white')))
self.dc.DrawRectangle(20, 20, 50, 50)
myApp = wx.App()
Mywin(None,'Drawing demo')
myApp.MainLoop()
A DC doesn't appear to support adding a tooltip, which is annoying, especially as the underlying wx widget appears to, as far as I can tell from the docs.
The best I can come up with at the moment, is to track the mouse movements but it is far from satisfactory and I suspect so limited that it might not be any help.
With those caveats made, I've supplied 3 options for the ToolTip like display. Namely, setting and unsetting the tooltip of the panel itself, a statusbar entry and a popup window.
Discard any you don't require.
import wx
class Mywin(wx.Frame):
def __init__(self, parent, title):
super(Mywin, self).__init__(parent, title=title, size=(500, 300))
self.tips = ["","Rectangle 1","Rectangle 2"]
self.rect = []
self.InitUI()
def InitUI(self):
self.panel = wx.Panel(self)
self.panel.SetBackgroundColour(wx.Colour('RED'))
self.Centre()
self.Show(True)
menuBar = wx.MenuBar()
RectangleButton = wx.Menu()
self.status = self.CreateStatusBar()
self.status.SetFieldsCount(number=2)
Item1 = RectangleButton.Append(wx.ID_ANY, 'Rectangle 1')
Item2 = RectangleButton.Append(wx.ID_ANY, 'Rectangle 2')
menuBar.Append(RectangleButton, 'Rectangles')
self.SetMenuBar(menuBar)
self.Bind(wx.EVT_MENU, self.DrawRect1, Item1)
self.Bind(wx.EVT_MENU, self.DrawRect2, Item2)
self.panel.Bind(wx.EVT_MOTION, self.MouseMovement)
def DrawRect1(self, e):
self.panel.SetBackgroundColour(wx.Colour('BLUE'))
self.Update()
self.dc = wx.ClientDC(self.panel)
self.dc.SetBrush(wx.Brush(wx.Colour('white')))
self.dc.DrawRectangle(10, 20, 100, 200)
#Note the position of the DC
self.rect = [x for x in self.dc.BoundingBox]
#Append the id
self.rect.append(1)
def DrawRect2(self, e):
self.panel.SetBackgroundColour(wx.Colour('GREEN'))
self.Update()
self.dc = wx.ClientDC(self.panel)
self.dc.SetBrush(wx.Brush(wx.Colour('white')))
self.dc.DrawRectangle(20, 20, 50, 50)
self.rect = [x for x in self.dc.BoundingBox]
self.rect.append(2)
def MouseMovement(self, event):
x,y = event.GetPosition()
self.panel.SetToolTip('')
self.status.SetStatusText('', 1)
if self.rect:
if x >= self.rect[0] and x <= self.rect[2] and y >= self.rect[1] and y <= self.rect[3]:
self.panel.SetToolTip(self.tips[self.rect[4]])
self.status.SetStatusText("Hovering over "+self.tips[self.rect[4]], 1)
win = Popup(self,self.rect[4],self.tips[self.rect[4]])
pos = self.GetScreenPosition()
win.Position(pos,(-1,-1))
win.Popup()
class Popup(wx.PopupTransientWindow):
def __init__(self, parent, id, id_text):
wx.PopupTransientWindow.__init__(self, parent)
panel = wx.Panel(self)
panel.SetBackgroundColour("gold")
text = wx.StaticText(panel, -1,
"This is a wx.PopupTransientWindow\n"
"Click mouse outside of it\n\n"
"Id of widget is "+str(id)+"\n"
"You are hovering over "+id_text)
# add other widgets here if required
sizer = wx.BoxSizer(wx.VERTICAL)
sizer.Add(text, 0, wx.ALL, 5)
panel.SetSizer(sizer)
sizer.Fit(panel)
sizer.Fit(self)
self.Layout()
myApp = wx.App()
Mywin(None,'Drawing demo')
myApp.MainLoop()
I am trying to put an entry widget with a label in one row using a horizontal box. However, the label expands vertically. It takes the initial height of the window and does not allow to shrink below it. I have tried all possible combinations of fill, expand, alignment etc. but it does not change.
How to fix it?
#!/usr/bin/env python3
import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk, Gdk
class MyWindow(Gtk.Window):
def __init__(self):
super(MyWindow, self).__init__()
self.init_ui()
def init_ui(self):
hbox = Gtk.Box(Gtk.Orientation.HORIZONTAL, 6)
hbox.set_homogeneous(True)
hbox.set_baseline_position(Gtk.BaselinePosition.CENTER)
entry = Gtk.Entry()
entry.modify_bg(Gtk.StateType.NORMAL, Gdk.Color(6400, 6400, 6440))
entry.connect("key-release-event", self.on_key_release)
hbox.pack_start(entry, False, False, 10)
self.label = Gtk.Label("Hello")
self.label.set_width_chars(15)
self.label.modify_bg(Gtk.StateType.NORMAL, Gdk.Color(40000, 40000, 40000))
hbox.pack_start(self.label, False, False, 10)
self.add(hbox)
self.set_title("Entry")
self.set_size_request(350, 250)
self.connect("destroy", Gtk.main_quit)
self.show_all()
def on_key_release(self, widget, event):
self.label.set_text(widget.get_text())
win = MyWindow()
Gtk.main()
Add another vertical box before the horizontal box:
#!/usr/bin/env python3
import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk, Gdk
class MyWindow(Gtk.Window):
def __init__(self):
super(MyWindow, self).__init__()
self.init_ui()
def init_ui(self):
hbox = Gtk.Box(orientation = Gtk.Orientation.HORIZONTAL, spacing = 6)
hbox.set_homogeneous(True)
hbox.set_baseline_position(Gtk.BaselinePosition.CENTER)
entry = Gtk.Entry()
entry.modify_bg(Gtk.StateType.NORMAL, Gdk.Color(6400, 6400, 6440))
entry.connect("key-release-event", self.on_key_release)
hbox.pack_start(entry, False, False, 10)
self.label = Gtk.Label("Hello")
self.label.set_width_chars(15)
self.label.modify_bg(Gtk.StateType.NORMAL, Gdk.Color(40000, 40000, 40000))
hbox.pack_start(self.label, False, False, 10)
vbox = Gtk.Box(orientation = Gtk.Orientation.VERTICAL)
vbox.pack_start(hbox, False, False, 0)
self.add(vbox)
self.set_title("Entry")
self.set_size_request(350, 250)
self.connect("destroy", Gtk.main_quit)
self.show_all()
def on_key_release(self, widget, event):
self.label.set_text(widget.get_text())
win = MyWindow()
Gtk.main()
As a side note, using non-keyword arguments does not always work properly in Python3 and Gtk, instead of hbox = Gtk.Box(Gtk.Orientation.HORIZONTAL, 6), use hbox = Gtk.Box(orientation = Gtk.Orientation.HORIZONTAL, spacing = 6)
I have popup being created along the edge of a window and I'd like it to expand the popup as the user types into its text field. This currently works, but the window is expanding to the right. Instead, I'd like the popup to expand to the left (and keep the right edge anchored in place).
My closest example that's kind of working is below. In it, I'm getting the size of the popup with every text input and then moving the popup based on its new size. I feel like this should work, but its not.
On the first text input the popup jumps to the left edge of my screen (x transformation only). On the second text input the popup jumps back to its original position. On a third text input the popup jumps back to the left edge of the screen. On the fourth input... You get the idea. I'd also like to mention that the overall growth of the window looks like it's growing from the center of the popup and not from the right edge.
I've noticed that after the button is clicked it remains highlighted until my mouse passes over it. Could this contributing to the problem?
Any thoughts or a better way to achieve this effect would be great, thanks!
from PySide import QtCore, QtGui
import maya.OpenMayaUI as mui
from shiboken import wrapInstance
def get_parent():
ptr = mui.MQtUtil.mainWindow()
return wrapInstance( long( ptr ), QtGui.QWidget )
############################################
class Tool_Window(QtGui.QDialog):
def __init__(self, parent = get_parent() ):
super(Tool_Window, self).__init__(parent)
# Commands
self.move_UI()
self.create_gui()
self.create_layout()
self.create_connections()
#-------------------------------------------
def create_gui(self):
self.button1 = QtGui.QPushButton()
self.button1.setMaximumWidth(50)
self.button2 = QtGui.QPushButton()
self.button2.setMaximumWidth(50)
self.button3 = QtGui.QPushButton()
self.button3.setMaximumWidth(50)
#-------------------------------------------
def create_layout(self):
layout = QtGui.QVBoxLayout()
layout.addWidget(self.button1)
layout.addWidget(self.button2)
layout.addWidget(self.button3)
blank_layout = QtGui.QVBoxLayout()
main_layout = QtGui.QHBoxLayout( self )
main_layout.addLayout(blank_layout)
main_layout.addLayout(layout)
layout.addStretch()
self.setLayout(layout)
#-------------------------------------------
def move_UI( self ):
''' Moves the UI to the cursor's position '''
pos = QtGui.QCursor.pos()
self.move(pos.x()+20, pos.y()+15)
#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#
def create_connections(self):
# Left click
self.button1.clicked.connect( self.on_left_click1 )
self.button2.clicked.connect( self.on_left_click2 )
self.button3.clicked.connect( self.on_left_click3 )
# Right click delete
delete = QtGui.QAction(self)
delete.setText("remove")
delete.triggered.connect(self.remove_button)
self.addAction(delete)
#-----#-----#-----#-----#-----#-----#-----#-----#-----#
def remove_button(self):
self.deleteLater()
def on_left_click1(self):
self.popup = Popup_Window( self, self.button1 ) # Passing button in so I can get it's position
self.popup.show()
def on_left_click2(self):
self.popup = Popup_Window( self, self.button2 )
self.popup.show()
def on_left_click3(self):
self.popup = Popup_Window( self, self.button3 )
self.popup.show()
############################################
class Popup_Window( QtGui.QDialog ):
def __init__( self, toolWindow, button ):
super( Popup_Window, self ).__init__()
self.__popup_filter = ClosePopupFilter()
self.installEventFilter(self.__popup_filter)
self.setWindowFlags(QtCore.Qt.Popup)
'''
self.setWindowFlags(QtCore.Qt.FramelessWindowHint |
QtCore.Qt.WindowStaysOnTopHint |
QtCore.Qt.CustomizeWindowHint |
QtCore.Qt.Tool)
'''
self.button_pos = button
self.toolWindow = toolWindow
self.setAttribute( QtCore.Qt.WA_DeleteOnClose )
self.resize(100, 100)
# Commands
self.create_gui()
self.create_layout()
self.create_connections()
self.move_UI()
#-------------------------------------------
def move_UI( self ): # Method that I use to place the popup window initially
self.line_edit.setFocus()
# Get button position
self.btn_global_point = self.button_pos.mapToGlobal(self.button_pos.rect().topLeft())
print self.btn_global_point
# Get window position
self.win_global_point = self.toolWindow.mapToGlobal(self.rect().topLeft())
print self.win_global_point
# Get popup Size
self.popup_size = self.mapToGlobal(self.rect().topRight())
print self.popup_size
# Move the window
self.move((self.win_global_point.x()-self.popup_size.x()), self.btn_global_point.y())
#-------------------------------------------
def create_gui( self ):
''' Visible GUI stuff '''
self.my_label = QtGui.QLabel("default text")
self.line_edit = QtGui.QLineEdit()
self.line_edit.setMaxLength( 30 )
self.push_btn = QtGui.QPushButton( "Hey" )
self.push_btn.setMaximumWidth( 30 )
#-------------------------------------------
def create_layout( self ):
self.button_layout = QtGui.QVBoxLayout()
self.button_layout.addWidget( self.my_label )
self.button_layout.addWidget( self.line_edit )
self.button_layout.addWidget( self.push_btn )
#self.button_layout.setContentsMargins(0, 0, 0, 0)
self.setLayout(self.button_layout)
#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#
def create_connections( self ):
self.line_edit.textChanged.connect( self.on_text_changed )
#-----#-----#-----#-----#-----#-----#-----#-----#-----#
def on_text_changed( self ):
typed_name = self.line_edit.text()
self.my_label.setText(typed_name)
self.move_UI() # I reuse the move method to move the ui on text edit
############################################
class ClosePopupFilter(QtCore.QObject):
''' Close popup window '''
def eventFilter(self, target, event):
if event.type() == QtCore.QEvent.WindowDeactivate:
target.close()
return False
if __name__ == '__main__':
# Things to fix PySide Maya bug
try:
test_ui.close()
test_ui.deleteLater()
except:
pass
test_ui = Tool_Window()
test_ui.show()
try:
test_ui.show()
except:
test_ui.close()
test_ui.deleteLater()
I've trimmed a little bit the code you provided in the OP and tried to put together an example that address your particular issue.
Some of the modifications I've done to the code:
trigger the move_UI within the resizeEvent of the Popup_Window ;
corrected the method move_UI in Popup_Window so that the popup does not blink on and off to one location to the other ;
moved the eventFilter directly within the Popup_Window ;
merged the functions handling the events for the button.clicked.connect in Tool_Window.
The solution is not perfect, there is still a little 'flicker' of the popup window when it is expanding and moving in Ubuntu. This is not very apparent in Windows7 however. If I think of another solution, I'll do an update.
from PySide import QtCore, QtGui
import sys
class Tool_Window(QtGui.QDialog): #=============================================
def __init__(self, parent=None):
super(Tool_Window, self).__init__(parent)
self.create_gui()
self.create_layout()
self.create_connections()
def create_gui(self): #=====================================================
self.button1 = QtGui.QPushButton('Button 1')
self.button2 = QtGui.QPushButton('Button 2')
self.button3 = QtGui.QPushButton('Button 3')
def create_layout(self): #==================================================
layout = QtGui.QVBoxLayout()
layout.addWidget(self.button1)
layout.addWidget(self.button2)
layout.addWidget(self.button3)
self.setLayout(layout)
def create_connections(self): #=============================================
self.button1.clicked.connect(self.on_lef_click )
self.button2.clicked.connect(self.on_lef_click )
self.button3.clicked.connect(self.on_lef_click )
def on_lef_click(self): #===================================================
button = self.sender()
self.popup = Popup_Window(self, button)
self.popup.show()
class Popup_Window( QtGui.QWidget ): #==========================================
def __init__( self, parent, button):
super(Popup_Window, self ).__init__(parent)
self.setWindowFlags(QtCore.Qt.Popup)
self.button = button
self.parent = parent
self.setAttribute(QtCore.Qt.WA_DeleteOnClose)
#---- set layout key dimension ----
self.min_width = 100
self.frame_thick = 10
self.setFixedWidth(self.min_width)
#---- init GUI ----
self.installEventFilter(self)
self.create_gui()
self.create_layout()
self.create_connections()
self.move_UI()
self.line_edit.setFocus()
def create_gui( self ): #===================================================
self.my_label = QtGui.QLabel("default text")
self.my_label.setAlignment(QtCore.Qt.AlignRight)
self.line_edit = QtGui.QLineEdit()
self.line_edit.setAlignment(QtCore.Qt.AlignRight)
self.line_edit.setMaxLength( 50 )
def create_layout( self ): #================================================
button_layout = QtGui.QGridLayout()
button_layout.addWidget(self.my_label, 0, 0)
button_layout.addWidget(self.line_edit, 1, 0)
button_layout.setContentsMargins(self.frame_thick, self.frame_thick,
self.frame_thick, self.frame_thick)
self.setLayout(button_layout)
def create_connections(self): #=============================================
self.line_edit.textChanged.connect(self.line_edit_text_changed)
def line_edit_text_changed(self, text): #==================================
#---- set the text in label ----
self.my_label.setText(text)
#---- determine new width of popup ----
fm = self.line_edit.fontMetrics()
txtWidth = fm.boundingRect(text).width() + 10 # Padding to the left.
# Value is arbitrary.
newWidth = max(txtWidth + self.frame_thick * 2, self.min_width)
self.setFixedWidth(newWidth)
def eventFilter(self, source, event): #=====================================
if event.type() == QtCore.QEvent.WindowDeactivate:
self.close()
return QtGui.QWidget.eventFilter(self, source, event)
def resizeEvent(self, event): #=============================================
self.move_UI()
QtGui.QWidget.resizeEvent(self, event)
def move_UI(self): # =======================================================
y_btn = self.button.mapToGlobal(QtCore.QPoint(0, 0)).y()
x_win = self.parent.mapToGlobal(QtCore.QPoint(0, 0)).x()
w_pop = self.frameGeometry().width()
x = x_win - w_pop - 12 # 12 is an arbitrary value.
y = y_btn
self.move(QtCore.QPoint(x, y))
if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
instance_1 = Tool_Window()
instance_1.show()
sys.exit(app.exec_())
This results in:
Update (2015-07-30): Popup shrink to the width of the content
I've extended the example so that now the popup starts with a minimum with of 100 that extends when the width of the text goes over this value. Also, the width of the popup will shrink, down to the minimum value of 100, if text is removed.
This is done by calculating the width of the text in QLineEdit when its content change and using the value to assign a fixed width to the popup window in the method line_edit_text_changed.
I am trying to set a colour to highlight a button. However, the modify_fg method only seems to set the focus ring's colour. modify_bg works as expected.
This is my code:
use Gtk2 qw/-init/;
my $window = Gtk2::Window->new;
$window->set_title("Window!");
my $button = Gtk2::Button->new("Coloured _button");
# does not affect text
$button->modify_fg(normal => Gtk2::Gdk::Color->new(0xffff, 0, 0));
$window->add($button);
$window->show_all;
Gtk2->main;
I'm also interested whether there is a standard colour for this sort of highlight, to blend in with the user's theme.
you can get the button's child label and modify its foreground, below is an example (python, let me know if there are troubles converting it to perl)
import gtk
class TestWindow:
def __init__(self):
window = gtk.Window(gtk.WINDOW_TOPLEVEL)
box = gtk.VBox()
button0 = gtk.Button("Test Button")
label0 = button0.get_children()[0]
label0.modify_fg(gtk.STATE_NORMAL, gtk.gdk.color_parse('red'))
button1 = gtk.Button(stock=gtk.STOCK_ABOUT)
alignment = button1.get_children()[0]
hbox = alignment.get_children()[0]
image, label1 = hbox.get_children()
label1.modify_fg(gtk.STATE_NORMAL, gtk.gdk.color_parse('blue'))
box.add(button0)
box.add(button1)
window.add(box)
window.set_size_request(200, 200)
window.show_all()
def close_application(self, widget, event, data=None):
gtk.main_quit()
return False
if __name__ == "__main__":
TestWindow()
gtk.main()
hope this helps, regards
All previous helped a lot...
All the following works ok!
my $beige = Gtk2::Gdk::Color->new (0xFFFF,0xFFFF,0xCCCC);
my $azul = Gtk2::Gdk::Color->new (0,0,0xCCCC);
my $rojo = Gtk2::Gdk::Color->new (0xCCCC,0,0);
$mw->modify_bg ("normal", $beige);
my $butOk = Gtk2::Button->new_with_label(" 🗹 ¡Ya Terminé!");
($butOk->get_children)[0]->modify_fg("normal", $azul);
($butOk->get_children)[0]->modify_font(Pango::FontDescription->from_string ("Serif Bold 27"));
my $imgBTN = Gtk2::Button->new();
my $img = Gtk2::Image->new_from_file("$imagen");
$imgBTN->set_property("image"=>$img);