在awesome中绘制后如何获取widget的宽度和高度?

How to get width and height of widget after it's been drawn in awesome?

情况是这样的:假设我有一个文本框,我想将其恰好放在屏幕的右侧,但仍让该文本框保持其自身的尺寸。换句话说,我只想指定字体,让文本框选择正确的尺寸,然后将其放置在屏幕边缘。知道尺寸就很简单了,以后就可以了

local awful = require("awful")
local wibox = require("wibox")

local text_widget = wibox.widget({
    widget = wibox.widget.textbox,
    font = "Roboto Medium 15",
    text = "hello world",
})

local rightmost_place = wibox.widget({
    layout = wibox.layout.manual,
    {
        text_widget,
        point = {
            y = 0, 
            -- You can't actually do the `text_widget.geometry.width`
            x = awful.screen.focused().geometry.width
                - text_widget.geometry.width
        },
        -- We're not setting these so the textbox
        -- will get its size automatically
        -- forced_width = 
        -- forced_height = 
    },
})

这样一来,每当我输入内容时,文本框就会变大,但它会根据 x 坐标自动重新定位。

此外,这不仅仅与文本框有关。我在使用其他小部件时遇到了同样的问题,所以我的问题是:是否有某种方法可以让小部件获得它们喜欢的尺寸,但仍能获得它们的几何形状以将它们重新定位到您想要的位置?

问题是小部件可以同时放置在多个位置(具有多个大小)。这对于某些情况很有用,例如文本时钟,所有屏幕都有一个实例(带有一个计时器)。这使得获得尺寸有点棘手。如果您不打算在多个位置使用该小部件,您可以作弊并添加 width/height 属性。

-- in the declarative syntax, add an `id`
id = `id_of_the_widget_with_size`,

-- Get the widget (somewhere outside of the declarative section)
local w = rightmost_place:get_children_by_id("id_of_the_widget_with_size")[1]
w._real_draw = w.draw
w.draw = function(self, context, cr, width, height)
    self.width, self.height = width, height
    w._real_draw(self, context, cr, width, height)
end

现在,理论上,小部件将具有 widthheight 属性。