FTXUI 7.0.3
C++ functional terminal UI.
Loading...
Searching...
No Matches
examples/component/button.cpp
Go to the documentation of this file.
1// Copyright 2020 Arthur Sonzogni. All rights reserved.
2// Use of this source code is governed by the MIT license that can be found in
3// the LICENSE file.
4#include <memory> // for shared_ptr, __shared_ptr_access
5#include <string> // for operator+, to_string
6
7#include "ftxui/component/app.hpp" // for App
8#include "ftxui/component/captured_mouse.hpp" // for ftxui
9#include "ftxui/component/component.hpp" // for Button, Horizontal, Renderer
10#include "ftxui/component/component_base.hpp" // for ComponentBase
11#include "ftxui/dom/elements.hpp" // for separator, gauge, text, Element, operator|, vbox, border
12
13using namespace ftxui;
14
15// 這是一個輔助函數,用於創建具有自定義樣式的按鈕。
16// 樣式由一個接受 EntryState 並返回 Element 的 lambda 函數定義。
17// 我們使用 `center` 將文本居中,然後使用 `border` 在按鈕周圍添加邊框,最後使用 `flex` 使按鈕填充可用空間。
18ButtonOption Style() {
19 auto option = ButtonOption::Animated();
20 option.transform = [](const EntryState& s) {
21 auto element = text(s.label);
22 if (s.focused) {
23 element |= bold;
24 }
25 return element | center | borderEmpty | flex;
26 };
27 return option;
28}
29
30int main() {
31 int value = 50;
32
33 // clang-format off
34 auto btn_dec_01 = Button("-1", [&] { value -= 1; }, Style());
35 auto btn_inc_01 = Button("+1", [&] { value += 1; }, Style());
36 auto btn_dec_10 = Button("-10", [&] { value -= 10; }, Style());
37 auto btn_inc_10 = Button("+10", [&] { value += 10; }, Style());
38 // clang-format on
39
40 // 元件樹。這定義了如何使用鍵盤導航。
41 // 選定的 `row` 用於獲取網格佈局。
42 int row = 0;
43 auto buttons = Container::Vertical({
44 Container::Horizontal({btn_dec_01, btn_inc_01}, &row) | flex,
45 Container::Horizontal({btn_dec_10, btn_inc_10}, &row) | flex,
46 });
47
48 // 修改它們在畫面上的渲染方式:
49 auto component = Renderer(buttons, [&] {
50 return vbox({
51 text("value = " + std::to_string(value)),
52 separator(),
53 buttons->Render() | flex,
54 }) |
55 flex | border;
56 });
57
58 auto screen = App::FitComponent();
59 screen.Loop(component);
60 return 0;
61}
ButtonOption Style()
Component Button(ConstStringRef label, std::function< void()> on_click, ButtonOption options=ButtonOption::Simple())
繪製一個按鈕。點擊時執行一個函式。
Component Renderer(Component child, std::function< Element()>)
回傳一個新的 Component,類似 |child|,但使用 |render| 作為 Component::Render() 事件。
Element text(std::string_view text)
顯示一段 UTF8 編碼的 Unicode 文字。
Element flex(Element child)
讓子元素依比例擴展以填滿容器中剩餘的空間。
Definition flex.cpp:94
Element bold(Element child)
使用粗體字型,用於需要更多強調的元素。
Definition bold.cpp:33
Element separator()
在兩個元素之間繪製垂直或水平分隔線。
Element vbox(Elements children)
一個垂直一個接一個顯示元素的容器。
Definition vbox.cpp:96
FTXUI ftxui:: 命名空間
Definition animation.hpp:11
const Element & element
Definition node.hpp:92
int value
Definition elements.hpp:192