use cxx::let_cxx_string;
use crate::ffi;
use crate::widget::AsWidget;
pub struct Label {
ptr: *mut ffi::QLabel,
has_parent: bool,
#[allow(dead_code)]
text: String,
}
impl Label {
pub fn new(text: impl Into<String>) -> Builder {
Builder::new(text.into())
}
pub fn text(&self) -> &str {
&self.text
}
pub fn set_text(&mut self, text: impl Into<String>) {
debug_assert!(!self.ptr.is_null(), "Label::set_text on null pointer");
self.text = text.into();
let_cxx_string!(c_text = &self.text);
unsafe {
ffi::QLabel_setText(self.ptr, &c_text);
}
}
}
impl AsWidget for Label {
fn widget_ptr(&self) -> *mut ffi::QWidget {
debug_assert!(!self.ptr.is_null(), "Label::widget_ptr on null pointer");
unsafe { ffi::toQWidget_QLabel(self.ptr) }
}
fn set_has_parent(&mut self) {
self.has_parent = true;
}
}
impl Drop for Label {
fn drop(&mut self) {
if self.ptr.is_null() {
return;
}
if !self.has_parent {
unsafe { ffi::QLabel_delete(self.ptr) };
}
self.ptr = std::ptr::null_mut();
}
}
pub struct Builder {
text: String,
parent: Option<*mut ffi::QWidget>,
}
impl Builder {
fn new(text: String) -> Self {
Self {
text,
parent: None,
}
}
pub fn parent(mut self, parent: &dyn AsWidget) -> Self {
self.parent = Some(parent.widget_ptr());
self
}
pub fn build(self) -> Label {
let_cxx_string!(c_text = &self.text);
let ptr = unsafe {
ffi::QLabel_new(
&c_text,
self.parent.unwrap_or(std::ptr::null_mut()),
)
};
debug_assert!(!ptr.is_null(), "QLabel_new returned null");
Label {
ptr,
has_parent: self.parent.is_some(),
text: self.text,
}
}
}